package cc.telecomdigital.tdstock.activity.groups.monitor;

import java.io.SequenceInputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import cc.telecomdigital.tdstock.CommonDefn;
//import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.StringUtils;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.IH_UserClient_HttpRequest_Report;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BMPBaseActivity;
import cc.telecomdigital.tdstock.activity.BaseActivity;
import cc.telecomdigital.tdstock.activity.groups.ForeignExchangeGroup;
import cc.telecomdigital.tdstock.activity.groups.IndexGroup;
import cc.telecomdigital.tdstock.activity.groups.MonitorGroup;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.foreignexchange.ForeignExchangeActivity;
import cc.telecomdigital.tdstock.activity.groups.index.BMPIndexActivity;
import cc.telecomdigital.tdstock.activity.groups.index.BMPIndexCOPListActivity;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.BookMarkUtil;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.MonitorUtil;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.SaveBookMarkAsyncTask;
import cc.telecomdigital.tdstock.activity.groups.more.MetalActivity;
import cc.telecomdigital.tdstock.activity.groups.more.OilQuoteActivity;
import cc.telecomdigital.tdstock.activity.groups.stock.BMPCurrentStockInfoActivity;
import cc.telecomdigital.tdstock.adapter.MonitorListItemAdapter;
import cc.telecomdigital.tdstock.adapter.MonitorViewHolder;
import cc.telecomdigital.tdstock.model.ForeignExchangeInfo;
import cc.telecomdigital.tdstock.model.IndexFuturesInfo;
import cc.telecomdigital.tdstock.model.IndexInfo;
import cc.telecomdigital.tdstock.model.IntlMetalInfo;
import cc.telecomdigital.tdstock.model.OilInfo;
import cc.telecomdigital.tdstock.model.StockInfo;
import cc.telecomdigital.tdstock.model.WorldFuturesInfo;
import cc.telecomdigital.tdstock.model.WorldIndexDelayInfo;
import cc.telecomdigital.tdstock.model.WorldIndexInfo;
import cc.telecomdigital.tdstock.utils.Futures;
import cc.telecomdigital.tdstock.utils.Fx;
import cc.telecomdigital.tdstock.utils.Index;
import cc.telecomdigital.tdstock.utils.Metal;
import cc.telecomdigital.tdstock.utils.Oil;
import cc.telecomdigital.tdstock.utils.Stock;
import cc.telecomdigital.tdstock.utils.WorldFutures;
import cc.telecomdigital.tdstock.utils.WorldIndex;
import cc.telecomdigital.tdstock.view.TouchListView;

/**
 * BMP Monitor
 * 
 * @author ouyangzhihui
 */
public class BMPPortfolioActivity extends BMPBaseActivity
{
	protected static Toast				_toast;

	protected static final String		TAG							= "BMPPortfolioActivity";
	private Button						_editMonitorBtn;
	private Button						_stockClassBtn;

	private TextView					_last_update_time; 
	
	private TouchListView				_listView;
	private boolean						_isEditing;
	private boolean						_isCustomerSubscribedItems	= false;

	private MonitorListItemAdapter		_monitor_item_Adapter;
	private Vector<MonitorViewHolder>	_monitorList;
	private Vector<MonitorViewHolder>	_dropList					= new Vector<MonitorViewHolder>();

	//private DBHelper					_dbHelper;
	private List<String[]>			_monitorItemFromServer;  //  size of one row is 2;
	private final static String COP_TAG = "9";

	private SharedPreferences			_prefsStockCode;

	private OnItemClickListener			_onItemClickListener;

	private String						_cameFrom;

	private long						lastRunntimeInOnResume		= 1l;
	private long						lastRunntimeInOnPause		= 1l;

//	private FetchOneSector				fetchOneSector;
//	private MonitorAsyncTask			monitorAsyncTask;

	@Override
	public void onCreate(final Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		TDStockLog.d(TAG, TAG + " onCreate");

		setContentView(R.layout.bmp_portfolio);

		// "期指Futures"，"上証SSEI" set Adapter
		// initFuturesAndSSEIAdapterType();

		_isEditing = false;
		_isCustomerSubscribedItems = false;

		Button _dj = (Button) findViewById(R.id.btn_dj);
		Button _f = (Button) findViewById(R.id.btn_f);

		_dj.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				Intent intent = new Intent(getApplicationContext(), MonitorNewsDjActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(MonitorNewsDjActivity.class, intent);
			}
		});

		_f.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				Intent intent = new Intent(getApplicationContext(), MonitorNewsFActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(MonitorNewsFActivity.class, intent);
			}
		});

		_listView = (TouchListView) findViewById(R.id.monitor_list);

		_onItemClickListener = new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View iView,
					int iIndex, long iArgs)
			{
				int objId;

				objId = parent.getId();
				switch (objId)
				{
					case R.id.monitor_list:
						if (iIndex != -1 && (!_isEditing))
						{
							TDStockLog.d(TAG, "item click");
							forwardToDestActivity(iIndex);
						}
						break;
				}
			}
		};

		_listView.setOnItemClickListener(_onItemClickListener);

		_listView.setDropListener(onDrop);
		_listView.setRemoveListener(onRemove);
		_monitorList = new Vector<MonitorViewHolder>();
		_monitor_item_Adapter = new MonitorListItemAdapter(LayoutInflater.from(this), _monitorList);
		// Adjust Size when display changes?
		_listView.setAdapter(_monitor_item_Adapter);

		_editMonitorBtn = (Button) findViewById(R.id.monitor_edit);
		_editMonitorBtn.setOnClickListener(new EditRowClickHandler(this));

		_stockClassBtn = (Button) findViewById(R.id.monitor_class);
		_stockClassBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(getApplicationContext(), StockSectorActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(StockSectorActivity.class, intent);
			}
		});

		//_dbHelper = new DBHelper(this);
		
		

//		Button _toolbutton_soccer = (Button) findViewById(R.id.toolbutton_soccer);// 足球
//		Button _toolbutton_horserace = (Button) findViewById(R.id.toolbutton_horserace);// 赛马
//
//		_toolbutton_soccer.setOnClickListener(
//				new View.OnClickListener()
//		{
//			@Override
//			public void onClick(View v)
//			{
//				forwardToSoccerActivity();
//			}
//		});
//
//		_toolbutton_horserace.setOnClickListener(
//				new View.OnClickListener()
//		{
//			@Override
//			public void onClick(View v)
//			{
//				forwardToHorseraceActivity();
//			}
//		});

		ViewGroup _btn_update_data = (ViewGroup) findViewById(R.id._btn_update_data);
		_btn_update_data.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "BMP update data");
				loadDataUpdateUI(_cameFrom, "false");
			}
		});
		_last_update_time = (TextView) findViewById(R.id._last_update_time);
	}

	private void resetTable()
	{
		if (_cameFrom.matches(CommonDefn.SECTOR_REG))
		{
			_editMonitorBtn.setVisibility(View.GONE);
		}
		else
		{
			_editMonitorBtn.setVisibility(View.VISIBLE);
		}
		
		if (_isCustomerSubscribedItems && BMPPortfolioActivity.class.getSimpleName().equals(_cameFrom.equals("") ? BMPPortfolioActivity.class.getSimpleName() : _cameFrom))
		{
			_monitor_item_Adapter.notifyDataSetChanged();
			return;
		}
		
		_listView.setClickable(false);
		_monitorList.clear();
		_monitor_item_Adapter.notifyDataSetChanged();
		_listView.setClickable(true);
	}

	private void updateAdapter(/*String code, */String[] otherFields/*, String adapter*/)
	{
		try
		{
			if (_isEditing)
			{
				TDStockLog.d(TAG, "don't allow to update the adapte yet for it is editing!");
				return;
			}
			String code = otherFields[4];
			String adapter = otherFields[5];
			boolean isUpdating = false;
			for (MonitorViewHolder monitorViewHolder : _monitorList)
			{
				if (monitorViewHolder.itemCode != null && monitorViewHolder.itemCode.getText().toString().equals(code)  && ( monitorViewHolder.adapter.equals(adapter)))
				{
					/*if(Futures.TypeName_Str.contains(code))
					{
						if(!monitorViewHolder.adapter.equals(adapter))
							continue;
					}*/
					
					TDStockLog.i(TAG, "generated ItemUpdate="+monitorViewHolder.itemCode.getText()+","+monitorViewHolder.itemName.getText()+","+monitorViewHolder.itemValue.getText()+","+monitorViewHolder.itemNet.getText()+","+monitorViewHolder.itemNetPercentage.getText());
					TDStockLog.i(TAG, "generated ItemUpdate="+monitorViewHolder.itemCode.getText()+"," + otherFields[0] + "," + otherFields[1] + "," + otherFields[2] + "," + otherFields[3]);
					isUpdating = true;
					monitorViewHolder.isEditable = _isEditing;
					monitorViewHolder.isTop20orSector = !_isCustomerSubscribedItems;
					//monitorViewHolder.adapter = adapter;
	
					if (monitorViewHolder.itemName == null)
					{
						TDStockLog.d(TAG, "generated a new view on itemName");
						monitorViewHolder.itemName = new TextView(this);
					}
					monitorViewHolder.itemName.setText(otherFields[0]);
	
					if (monitorViewHolder.itemValue == null)
					{
						TDStockLog.d(TAG, "generated a new view on itemValue");
						monitorViewHolder.itemValue = new TextView(this);
					}
					monitorViewHolder.itemValue.setText(otherFields[1]);
					if (monitorViewHolder.itemNet == null)
					{
						TDStockLog.d(TAG, "generated a new view on itemNet");
						monitorViewHolder.itemNet = new TextView(this);
					}
					monitorViewHolder.itemNet.setText(otherFields[2]);
					if (monitorViewHolder.itemNetPercentage == null)
					{
						TDStockLog.d(TAG, "generated a new view on itemNetPercentage");
						monitorViewHolder.itemNetPercentage = new TextView(
								this);
					}
					monitorViewHolder.itemNetPercentage.setText(otherFields[3]);
					TDStockLog.d(TAG, String.format(
							"ready to update the item : %s , thread id: %d",
							code, Thread.currentThread().getId()));
					break;
				}
			}
	
			if (!isUpdating)
			{
				// append a record
				MonitorViewHolder monitorViewHolder = new MonitorViewHolder();
				monitorViewHolder.isEditable = _isEditing;
				monitorViewHolder.isTop20orSector = !_isCustomerSubscribedItems;
				//monitorViewHolder.adapter = adapter;
				monitorViewHolder.itemCode = new TextView(this);
				monitorViewHolder.itemCode.setText(code);
	
				monitorViewHolder.itemName = new TextView(this);
				monitorViewHolder.itemName.setText(otherFields[0]);
	
				monitorViewHolder.itemValue = new TextView(this);
				monitorViewHolder.itemValue.setText(otherFields[1] == null ? ""
						: otherFields[1]);
	
				monitorViewHolder.itemNet = new TextView(this);
				monitorViewHolder.itemNet.setText(otherFields[2] == null ? ""
						: otherFields[2]);
	
				monitorViewHolder.itemNetPercentage = new TextView(this);
				monitorViewHolder.itemNetPercentage
						.setText(otherFields[3] == null ? "" : otherFields[3]);
				TDStockLog.d(TAG, "ready to insert the item :" + code);
				_monitorList.add(monitorViewHolder);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/*
 	private class EditRowClickHandler extends DefaultClickHandler
	{
		EditRowClickHandler(Context context)
		{
			super(context);
		}

		@Override
		public void onDefaultAction()
		{
			if (_toast != null)
				_toast.cancel();

			if (_editMonitorBtn.getText().toString().equals(
					getResources().getString(R.string.monitor_finish)))
			{
				// ready to save to the database;
				int totalmodifiedRecord = _monitorList.size() + _dropList.size();
				if (totalmodifiedRecord >= 1)
				{
					String[] items = new String[totalmodifiedRecord];
					String[] adapter = new String[totalmodifiedRecord];
					int[] index = new int[totalmodifiedRecord];
					int item = 0;

					for (MonitorViewHolder holder : _monitorList)
					{
						items[item] = holder.itemCode.getText().toString();
						adapter[item] = holder.adapter;
						if ("SSE1".equals(items[item]) || "SS300".equals(items[item]) || "SSEA".equals(items[item]) || "SSEB".equals(items[item]))
						{
							adapter[item] = WorldIndexInfo.ADAPTER + WorldIndexDelayInfo.ADAPTER;
						}
						TDStockLog.d(TAG, "1 item=" + items[item] + " , adapter=" + adapter[item]);
						index[item] = item + 1;
						item++;
					}

					for (MonitorViewHolder holder : _dropList)
					{
						items[item] = holder.itemCode.getText().toString();
						adapter[item] = holder.adapter;
						if ("SSE1".equals(items[item]) || "SS300".equals(items[item]) || "SSEA".equals(items[item]) || "SSEB".equals(items[item]))
						{
							adapter[item] = WorldIndexInfo.ADAPTER + WorldIndexDelayInfo.ADAPTER;
						}
						TDStockLog.d(TAG, "2 item=" + items[item] + " , adapter=" + adapter[item]);
						index[item] = -1; // as a mark will delete the record
						item++;
					}
					int customerId = ((ITDLApplication) getApplicationContext())
							.getUserId(-1);
					boolean result = _dbHelper.updateSubscribeItems(
							customerId, items, adapter, index);
					TDStockLog.d(TAG, "save to subscription and  the result is "
							+ (result ? " success" : "failure"));
				}
			}
			else
			{
				try
				{
					showToast(BMPPortfolioActivity.this, 0);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			_isEditing = !_isEditing;
			TDStockLog.d(TAG, "isEditing =  " + (_isEditing ? " true" : "false"));
			_editMonitorBtn.setText(_isEditing ? R.string.monitor_finish : R.string.monitor_edit);
			_listView.SetEditingMode(_isEditing);
			for (MonitorViewHolder holder : _monitorList)
			{
				holder.isEditable = _isEditing;
			}
			_monitor_item_Adapter.notifyDataSetChanged();
			TDStockLog.d(TAG, "monitor_item_Adapter.notifyDataSetChanged! +  list size: " + _monitorList.size());
		}
	} */
	
	
	private class EditRowClickHandler extends DefaultClickHandler
	{
		EditRowClickHandler(Context context)
		{
			super(context);
		}

		@Override
		public void onDefaultAction()
		{
			if (_toast != null)
				_toast.cancel();

			if (_editMonitorBtn.getText().toString().equals(
					getResources().getString(R.string.monitor_finish)))
			{
				/*				if(_monitorList==null){
									return;
								}
								for (int i = 0; i <_monitorList.size(); i++) {
									if(_monitorList.get(i).delBtn!=null&&_monitorList.get(i).delBtn.getVisibility()!=View.GONE){
										_monitorList.get(i).delBtn.setVisibility(View.GONE);
									}
								}*/

				// ready to save to the database;
				int totalmodifiedRecord = _monitorList.size() + _dropList.size();
				String[] items = new String[totalmodifiedRecord];
				//String[] adapter = new String[totalmodifiedRecord];
				int[] index = new int[totalmodifiedRecord];
				int[] type = new int[totalmodifiedRecord];
				int item = 0;
				if (totalmodifiedRecord >= 1)
				{

					for (MonitorViewHolder holder : _monitorList)
					{
						items[item] = holder.itemCode.getText()
								.toString();
						/*adapter[item] = holder.adapter;
						if ("SSE1".equals(items[item])
								|| "SS300".equals(items[item])
								|| "SSEA".equals(items[item])
								|| "SSEB".equals(items[item]))
						{
							adapter[item] = WorldIndexInfo.ADAPTER
									+ WorldIndexDelayInfo.ADAPTER;
						}
						TDStockLog.d(TAG, "1 item=" + items[item]
								+ " , adapter=" + adapter[item]);*/
						type[item] = holder.type;
						item++;
					}
					List<String[]> lists = new ArrayList<String[]>();
					for (int i = 0; i < index.length; i++)
					{
						if (items[i] != null)
						{
							String[] temp = new String[2];
							temp[0] = items[i];
							temp[1] = type[i] + "";
							lists.add(temp);
						}
					}
					TDStockLog.d(TAG, lists.size()+"");
					new SaveBookMarkAsyncTask(BMPPortfolioActivity.this,
							MonitorUtil.getInstance(), "", lists)
							.execute();
				}

			}
			else
			{
				try
				{
					// showToast(PortfolioActivity.this, 0,
					// getResources().getString(R.string.monitor_edit_drag_tips));
					showToast(BMPPortfolioActivity.this, 0);
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			_isEditing = !_isEditing;
			TDStockLog.d(TAG, "isEditing =  "
					+ (_isEditing ? " true" : "false"));
			_editMonitorBtn.setText(_isEditing ? R.string.monitor_finish
					: R.string.monitor_edit);
			_listView.SetEditingMode(_isEditing);
			for (MonitorViewHolder holder : _monitorList)
			{
				holder.isEditable = _isEditing;
			}
			_monitor_item_Adapter.notifyDataSetChanged();
			TDStockLog.d(TAG,
					"monitor_item_Adapter.notifyDataSetChanged! +  list size: "
							+ _monitorList.size());

		}
	}

	public void updateBackground(Object handlerId, int color)
	{
		int childCount = _listView.getChildCount();
		for (int index = 0; index < childCount; index++)
		{
			if (_listView.getChildAt(index) instanceof RelativeLayout)
			{
				RelativeLayout tmpHolder = (RelativeLayout) _listView.getChildAt(index);
				Object itemCode = tmpHolder.findViewById(R.id.monitor_item_code);

				if (itemCode != null)
				{
					if (((TextView) itemCode).getText().toString().equals(
							handlerId))
					{
						TextView itemValue = (TextView) tmpHolder
								.findViewById(R.id.monitor_item_value);
						TextView netValue = (TextView) tmpHolder
								.findViewById(R.id.monitor_item_net);
						TextView netPercentageValue = (TextView) tmpHolder
								.findViewById(R.id.monitor_item_netpercentage);
						if (itemValue != null && netValue != null
								&& netPercentageValue != null)
						{
							if (color <= 0)
							{
								itemValue.setBackgroundDrawable(null);
								itemValue.postInvalidate();
								netValue.setBackgroundDrawable(null);
								netValue.postInvalidate();
								netPercentageValue
										.setBackgroundDrawable(null);
								netPercentageValue.postInvalidate();
							}
							else
							{
								itemValue.setBackgroundColor(color);
								itemValue.postInvalidate();
								netValue.setBackgroundColor(color);
								netValue.postInvalidate();
								netPercentageValue
										.setBackgroundColor(color);
								netPercentageValue.postInvalidate();
							}
						}
						break;
					}
				}
			}
		}
	}

	private TouchListView.DropListener		onDrop		= new TouchListView.DropListener()
														{
															@Override
															public void drop(
																	int from,
																	int to)
														{
															MonitorViewHolder item = _monitorList
																	.get(from);
															_monitorList
																	.remove(item);
															_monitorList
																	.add(
																			to,
																			item);
															_listView
																	.invalidateViews();
														}
														};

	private TouchListView.RemoveListener	onRemove	= new TouchListView.RemoveListener()
														{
															@Override
															public void remove(
																	int which)
														{
															_dropList
																	.add(_monitorList
																			.get(which));
															_monitorList
																	.remove(_monitorList
																			.get(which));
															_listView
																	.invalidateViews();
														}

														};

	private void forwardToDestActivity(final int position)
	{
		if (position < 0 || _monitorList.size() < position + 1)
		{
			return;
		}
		if (TextUtils.isDigitsOnly(_monitorList.get(position).itemCode
				.getText().toString()))
		{
			_prefsStockCode = getSharedPreferences(
					CommonDefn.SYSTEM_CURRENT_SETTING,
					Context.MODE_PRIVATE);
			_prefsStockCode.edit().putString(
					CommonDefn.PREFERENCE_STOCK_CODE,
					_monitorList.get(position).itemCode.getText()
							.toString()).commit();

			Intent intent = new Intent(getApplicationContext(), BMPCurrentStockInfoActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);

			SwitchTabHostActivity(0, StockGroup.GetActivityGroupHostControl(), BMPCurrentStockInfoActivity.class, intent);
		}
		else if (ForeignExchangeInfo.ADAPTER.equals(_monitorList
				.get(position).adapter)
				&& ForeignExchangeInfo.CODE_TO_NAME
						.containsKey(_monitorList.get(position).itemCode
								.getText().toString()))
		{
			((ITDLApplication) getApplicationContext()).putString(
					CommonDefn.FROM_MONITOR_TO_ACTIVITY_FORWARDING_ITEM,
					_monitorList.get(position).itemCode.getText()
							.toString());
			TDStockLog.d(TAG, "forwading item="
					+ _monitorList.get(position).itemCode.getText()
							.toString());

			if (ForeignExchangeGroup.group != null)
			{
				Intent intent = new Intent(getApplicationContext(),
						ForeignExchangeActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchTabHostActivity(3, ForeignExchangeGroup.GetActivityGroupHostControl(), ForeignExchangeActivity.class, intent);
			}
			else
			{
				ForeignExchangeGroup.forceToGoToRelatingTab();
			}
		}
		else if (IntlMetalInfo.ADAPTER.equalsIgnoreCase(_monitorList.get(position).adapter))
		{
			((ITDLApplication) getApplicationContext()).putString(
					CommonDefn.ACTIVITY_CAME_FROM_KEY, this.getClass()
							.getSimpleName());

			if (MoreGroup.group != null)
			{
				Intent intent = new Intent(getApplicationContext(), MetalActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchTabHostActivity(4, MoreGroup.GetActivityGroupHostControl(), MetalActivity.class, intent);
			}
			else
			{
				MoreGroup.forceToGoToRelatingTab();
			}
		}
		else if (OilInfo.ADAPTER.equalsIgnoreCase(_monitorList.get(position).adapter))
		{
			if (MoreGroup.group == null)
			{
				MoreGroup.forceToGoToRelatingTab();
			}
			Intent intent = new Intent(getApplicationContext(), OilQuoteActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			SwitchTabHostActivity(4, MoreGroup.GetActivityGroupHostControl(), OilQuoteActivity.class, intent);
		}
		else if (_monitorList.get(position).isCop)
		{
			((ITDLApplication) getApplicationContext()).putString(CommonDefn.FROM_MONITOR_TO_ACTIVITY_FORWARDING_ITEM, _monitorList.get(position).itemCode.getText().toString());
			TDStockLog.d(TAG, "forwading item=" + _monitorList.get(position).itemCode.getText().toString());

			if (IndexGroup.group == null)
			{
				IndexGroup.forceToGoToRelatingTab();
			}
			else
			{
				Intent intent = new Intent(getApplicationContext(), BMPIndexCOPListActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchTabHostActivity(2, IndexGroup.GetActivityGroupHostControl(), BMPIndexCOPListActivity.class, intent);
			}
		}
		else
		{
			((ITDLApplication) getApplicationContext()).putString(
					CommonDefn.FROM_MONITOR_TO_ACTIVITY_FORWARDING_ITEM,
					_monitorList.get(position).itemCode.getText()
							.toString());
			TDStockLog.d(TAG, "forwading item="
					+ _monitorList.get(position).itemCode.getText()
							.toString());
			((ITDLApplication) getApplicationContext())
					.putString(
							CommonDefn.FROM_MONITOR_TO_ACTIVITY_FORWARDING_ADAPTER,
							_monitorList.get(position).adapter);

			if (IndexGroup.group != null)
			{
				Intent intent = new Intent(getApplicationContext(), BMPIndexActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchTabHostActivity(2, IndexGroup.GetActivityGroupHostControl(), BMPIndexActivity.class, intent);
			}
			else
			{
				IndexGroup.forceToGoToRelatingTab();
			}
		}
	}

	private boolean isItemExist(final String itemName)
	{
		boolean result = true;
		for (MonitorViewHolder holder : _dropList)
		{
			if (holder.itemCode != null
					&& itemName.equals(holder.itemCode.getText()
							.toString()))
			{
				result = false;
				break;
			}
		}
		return result;
	}

	private static void sortAsNumbersByAsc(String[] source)
	{
		int length = source.length;
		for (int index = 0; index < length; index++)
		{
			for (int item = index + 1; item < length; item++)
			{
				if (Integer.parseInt(source[index], 10) > Integer.parseInt(
						source[item], 10))
				{
					String tmp = source[index];
					source[index] = source[item];
					source[item] = tmp;
				}
			}
		}
	}

//	public synchronized void exitApp()
//	{
//		super.exitApp();
//	}

	public static void showToast(Activity paramActivity, int paramInt)
	{
		if (_toast == null)
			_toast = new Toast(paramActivity);

		View localView = paramActivity.getLayoutInflater().inflate(
				R.layout.richtoast_for_monitor_edit_tips, null);
		_toast.setView(localView);
		_toast.setDuration(Toast.LENGTH_LONG);
		_toast.show();
	}

//	@Override
//	protected void onNewIntent(Intent intent)
//	{
//		super.onNewIntent(intent);
//		updateListViewUnderUnEditMode();
//		TDStockLog.d(TAG, "onNewIntent executed !");
//
//		if (appHost.LSClient_IsConnected())
//		{
//			LightStreamerUnsubscribeAll();
//		}
//	}

	private void updateListViewUnderUnEditMode()
	{
		this._isEditing = false;
		for (MonitorViewHolder holder : _monitorList)
		{
			holder.isEditable = _isEditing;
		}
		if (_listView.getVisibility() == View.VISIBLE)
			_monitor_item_Adapter.notifyDataSetChanged();
	}

	/**
	 * I don't know why this method execute twice sometime(it happens at the
	 * time when i unlock the screen for this page)
	 */
	@Override
	protected void onResume()
	{
		super.SetExectuHttpRequestOnResume(false);
		super.onResume();
		TDStockLog.d(TAG, TAG + " onResume");
		
		if(appHost.screenIsLocked)
			return;

		final String cameFrom = ((ITDLApplication) getApplicationContext()).getString(CommonDefn.ACTIVITY_CAME_FROM_KEY) == null 
				? BMPPortfolioActivity.class.getSimpleName() : 
				((ITDLApplication) getApplicationContext()).getString(CommonDefn.ACTIVITY_CAME_FROM_KEY);

		_cameFrom = cameFrom; // save the come from page
		
		//_monitorItemFromServer =  MonitorUtil.getInstance().getItems(BMPPortfolioActivity.this);
		super.ShowHideDialog(GetBMPMonitorItemDataFromServer());
		// do nothing if there's no any subscribed item
/*		if (BMPPortfolioActivity.class.getSimpleName().equals(cameFrom))
		{
			_editMonitorBtn.setVisibility(View.VISIBLE);
			_editMonitorBtn.setText(_isEditing ? R.string.monitor_finish : R.string.monitor_edit);
			
			//List<String[]> items = _dbHelper.getSubscribeItemsByUserId(1);
			if(_monitorItemFromServer == null || _monitorItemFromServer.size() < 1)
			{
				_monitorList.clear();
				_listView.setClickable(false);
				_monitor_item_Adapter.notifyDataSetChanged();
				_listView.setClickable(true);
				return;
			}
		}
		*/
/*		if (System.currentTimeMillis() - lastRunntimeInOnResume < 1000l && lastRunntimeInOnResume != 1l)
		{
			for (MonitorViewHolder holder : _monitorList)
			{
				holder.isEditable = _isEditing;
			}
			_monitor_item_Adapter.notifyDataSetChanged();
			return;
		} // don't execute twice during a short term
		lastRunntimeInOnResume = System.currentTimeMillis();

		if (_dbHelper == null)
		{
			_dbHelper = new DBHelper(this);
		}

		if (_dropList != null)
		{
			_dropList.clear();
		}

		resetTable();

		if (_iconTip != null && mWindowManager != null)
		{
			mWindowManager.removeViewImmediate(_iconTip);
			_iconTip = null;
		}
		if (BaseActivity._iconTip != null && BaseActivity.mWindowManager != null)
		{
			BaseActivity.mWindowManager.removeViewImmediate(BaseActivity._iconTip);
			BaseActivity._iconTip = null;
		}
		if(BMPBaseActivity._iconTip != null && BMPBaseActivity.mWindowManager != null)
		{
			BMPBaseActivity.mWindowManager.removeViewImmediate(BMPBaseActivity._iconTip);
			BMPBaseActivity._iconTip = null;
		}
		
		

		if (_isEditing)
		{
			_isEditing = false;
			// Reset Item to non-editing mdode
			_listView.SetEditingMode(_isEditing);
		}
		_editMonitorBtn.setText(_isEditing ? R.string.monitor_finish : R.string.monitor_edit);

		loadDataUpdateUI(_cameFrom); // get data update ui
*/	}

	@Override
	protected void onPause()
	{
		super.onPause();
		TDStockLog.d(TAG, TAG + " onPause");

		_isEditing = false;
//		if (monitorAsyncTask != null)
//		{
//			monitorAsyncTask.cancel(true);
//			monitorAsyncTask = null;
//		}
//		if(fetchOneSector != null)
//		{
//			fetchOneSector.cancel(true);
//			fetchOneSector = null;
//		}
//		BaseAsyncTask.cancelAllTask();
		if (_toast != null)
			_toast.cancel();
		// 離開當前頁面，關閉太陽花
		// clearSunFlower(); // by ouyangzhihui 2011-08-11

		if (System.currentTimeMillis() - lastRunntimeInOnPause < 500l
				&& lastRunntimeInOnPause != 1l)
		{
			TDStockLog.d(TAG, "don't execute twice during a short term in onPause!");
			return;
		} // don't execute twice during a short term
		lastRunntimeInOnPause = System.currentTimeMillis();

	}

	@Override
	protected void onStart()
	{
		super.onStart();
		TDStockLog.d(TAG, TAG + " onStart");

	/*	if (_dbHelper == null)
		{
			_dbHelper = new DBHelper(this);
		}*/
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();
		TDStockLog.d(TAG, TAG + " onRestart");

		/*if (_dbHelper == null)
		{
			_dbHelper = new DBHelper(this);
		}*/

		if (_listView != null)
			_listView.setVisibility(View.VISIBLE);
	}

	@Override
	protected void onStop()
	{
		super.onStop();
		TDStockLog.d(TAG, TAG + " onStop");

		if (_listView != null)
			_listView.setVisibility(View.GONE);
		updateListViewUnderUnEditMode();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		TDStockLog.d(TAG, TAG + " onDestroy");

//		this._dbHelper.cleanup();
	}

	@Override
	public void onBackPressed()
	{
		super.onBackPressed();
		TDStockLog.d(TAG, TAG + " onBackPressed");
	}

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		//share the same tab with  more group,
		return MonitorGroup.GetActivityGroupHostControl() == null ?  MoreGroup.GetActivityGroupHostControl() : MonitorGroup.GetActivityGroupHostControl() ;
	}
	
	private void GetFetchOneSectorData(String cameFrom)
	{
		((ITDLApplication) getApplicationContext()).putString(CommonDefn.ACTIVITY_CAME_FROM_KEY, "");

//		if(fetchOneSector == null)
//		{
//			fetchOneSector = new FetchOneSector(getMyOwnContext(), isSunflower.length <= 0);
//			fetchOneSector.execute(cameFrom);
//		}
		
		SendHttpRequestBySector(cameFrom.replace("sector=", ""));
	}
	private void GetCustomerItemData(String... isSunflower)
	{
	/*	List<String[]> items = _dbHelper.getSubscribeItemsByUserId(1);

		// do nothing if there's no any subscribed item
		if (items == null || items.size() < 1)
		{
			return;
		}*/
		
//		if (monitorAsyncTask == null)
//		{
//			monitorAsyncTask = new MonitorAsyncTask(getMyOwnContext(), isSunflower.length <= 0);
//			monitorAsyncTask.execute();
//		}
		if( _monitorItemFromServer != null)
			SendHttpRequest();
	}

	private void loadDataUpdateUI(String cameFrom, String... isSunflower)
	{
//		Toast.makeText(getMyOwnContext(), TAG + " Update Data", Toast.LENGTH_SHORT).show();
		
		_isCustomerSubscribedItems = false;
		
		TDStockLog.i(TAG, "TAG=cameFrom=" + cameFrom);
		
		if(isSunflower.length <= 0)
			SetShowProgressView(true);
		else
			SetShowProgressView(false);
		
		if (cameFrom.matches(CommonDefn.SECTOR_REG))
		{
			GetFetchOneSectorData(cameFrom);
		}
		else
		{
			GetCustomerItemData(isSunflower);
		}
	}
	
//	private class FetchOneSector extends BaseAsyncTask
//	{
//		private static final String	SOURCE_URL				= "http://%s/iphone/getStockSectorSc.do?test=test";
//
//		private boolean				_isExceptionHappened	= false;
//		private String				_destURL;
//		private String[]			_stockCodes;
//		private String				_stockCodesStr;
//		
//		private List<String[]> fields_list = new ArrayList<String[]>();
//		private boolean isSunflower = true;
//
//		public FetchOneSector(Context context)
//		{
//			super(context);
//		}
//		
//		public FetchOneSector(Context context, boolean isSunflower)
//		{
//			super(context);
//			this.isSunflower = isSunflower;
//		}
//
//		@Override
//		protected void onPreExecute()
//		{
//			if(isSunflower)
//				super.onPreExecute();
//			_destURL = String.format(SOURCE_URL, CustomerInfo.getWebServerHost());
//		}
//
//		// automatically done on worker thread (separate from UI thread)
//		@Override
//		protected Void doInBackground(String... params)
//		{
//			_isExceptionHappened = false;
//			String tag = params[0];
//			if (!tag.startsWith("&"))
//			{
//				tag = "&" + tag;
//			}
//			String account = ((ITDLApplication) getApplicationContext()).getSessionAccount();
//			String token = ((ITDLApplication) getApplicationContext()).getSessionToken();
//			String addParam = new StringBuffer("&account=").append(account).append("&token=").append(token).append(tag).toString();
//			_destURL += addParam;
//
//			final DefaultHttpClient client = new DefaultHttpClient();
//			HttpParams httpParams = client.getParams();
//			HttpConnectionParams.setConnectionTimeout(httpParams, CommonDefn.CONNECTION_TIMEOUT * 2);
//			HttpConnectionParams.setSoTimeout(httpParams, CommonDefn.CONNECTION_TIMEOUT * 3);
//			client.setParams(httpParams);
//
//			try
//			{
//				HttpGet httpMethod = new HttpGet(_destURL);
//
//				TDStockLog.d(TAG, "url-->" + _destURL);
//
//				client.execute(httpMethod, new ResponseHandler<String>()
//				{
//					public String handleResponse(HttpResponse response)
//					{
//						// when the response happens close the notification and
//						// update UI
//						StatusLine status = response.getStatusLine();
//						TDStockLog.d(TAG, " statusCode - " + status.getStatusCode());
//						TDStockLog.d(TAG, " statusReasonPhrase - " + status.getReasonPhrase());
//						try
//						{
//							HttpEntity entity = response.getEntity();
//
//							String httpResponse = StringUtils.inputStreamToString(entity.getContent());
//
//							Map<String, String> map = StringUtils.stringToMap(httpResponse, "Status,ErrorMessage");
//							if (map.containsKey("Status") && "-1".equals(map.get("Status").trim()))
//							{
//								Intent notifyChanges = new Intent(CommonDefn.RECEIVER_SESSION_EXPIRED, null);
//								sendBroadcast(notifyChanges);
//							}
//
//							String[] result = httpResponse.split("(<[/]{0,1}StockCode>)");
//							_stockCodes = new String[result.length - 2];
//							StringBuffer buff = new StringBuffer();
//							java.lang.System.arraycopy(result, 1, _stockCodes, 0, result.length - 2);
//							for (int index = 0; index < _stockCodes.length; index++)
//							{
//								if (TextUtils.isDigitsOnly(_stockCodes[index]))
//									buff.append(_stockCodes[index]).append(",");
//							}
//							TDStockLog.d(TAG, "stocks:" + buff.toString());
//
//							// reset the _stockCodes;
//							_stockCodes = buff.toString().split("[,]");
//
//							sortAsNumbersByAsc(_stockCodes);
//							buff.delete(0, buff.toString().length());
//							for (int index = 0; index < _stockCodes.length; index++)
//							{
//								buff.append(_stockCodes[index]).append(",");
//							}
//
//							_stockCodesStr = buff.toString();
//							TDStockLog.d(TAG, "sorted stocks:" + buff.toString());
//						}
//						catch (Exception e)
//						{
//							_isExceptionHappened = true;
//							TDStockLog.e(TAG, "exception " + e.toString());
//						}
//						return "";
//					}
//				});
//			}
//			catch (Exception e)
//			{
//				_isExceptionHappened = true;
//				TDStockLog.e(TAG, "exception " + e.toString());
//			}
//			
//			try
//			{
//				if (_stockCodes != null && _stockCodes.length >= 1)
//				{
//					// stock
//					Map<String, Stock> stockList = HttpDataBaseUtils.getDataByStock_Monitor2(_stockCodesStr, ((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
////					List<Stock> stockList = HttpDataBaseUtils.getDataByStock_Monitor(_stockCodes);
//					TDStockLog.d(TAG, "sorted stocks size="+_stockCodes.length+" , "+stockList.size());
//					for (int i = 0; i < stockList.size(); i++)
//					{
//						String[] fields = OnUpdateStock(stockList.get(_stockCodes[i]));
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//			}
//			catch(Exception e)
//			{
//				TDStockLog.e(TAG, "exception="+e.toString());
//			}
//			
//			return null;
//		}
//
//		// can use UI thread here
//		@Override
//		protected void onPostExecute(Void result)
//		{
//			if(isSunflower)
//				super.onPostExecute(result);
//			fetchOneSector = null;
//			
//			if (_isExceptionHappened)
//			{
//				new CustomizeDialog(BMPPortfolioActivity.this.getParent(),
//						getResources().getString(R.string.info),
//						getResources().getString(R.string.no_data_tips)).show();
//				return;
//			}
//			
//			// removeRows();
//			_monitorList.clear();
//
//			if (_stockCodes == null || _stockCodes.length < 1)
//			{
//				new CustomizeDialog(BMPPortfolioActivity.this.getParent(),
//						getResources().getString(R.string.info),
//						getResources().getString(R.string.no_data_tips)).show();
//				return;
//			}
//			else
//			{
//				for (final String stk : _stockCodes)
//				{
//					MonitorViewHolder monitorViewHolder = new MonitorViewHolder();
//					monitorViewHolder.isEditable = _isEditing;
//					monitorViewHolder.adapter = StockInfo.ADAPTER;
//					monitorViewHolder.isTop20orSector = true;
//					monitorViewHolder.itemCode = new TextView(BMPPortfolioActivity.this);
//					monitorViewHolder.itemCode.setText(stk);
//					monitorViewHolder.itemName = new TextView(BMPPortfolioActivity.this);
//					monitorViewHolder.itemValue = new TextView(BMPPortfolioActivity.this);
//					monitorViewHolder.itemNet = new TextView(BMPPortfolioActivity.this);
//					monitorViewHolder.itemNetPercentage = new TextView(BMPPortfolioActivity.this);
//
//					_monitorList.add(monitorViewHolder);
//				}
//				
//				_monitor_item_Adapter.notifyDataSetChanged();
//				TDStockLog.d(TAG, "updated  _monitor_item_Adapter!");
//			}
//			
//			// set the index order by number asc
//			final Runnable job = new Runnable()
//			{
//				public void run()
//				{
//					try
//					{
//						for(int i = 0; i < fields_list.size(); i++)
//						{
//							updateAdapter(fields_list.get(i));
//						}
//						_listView.setClickable(false);
//						_monitor_item_Adapter.notifyDataSetChanged();
//						_listView.setClickable(true);
//						
//						GetTimeData();
//					}
//					catch (Exception e)
//					{
//						e.printStackTrace();
//					}
//				}
//			};
//			
//			try
//			{
//				new Thread()
//				{
//					public void run()
//					{
//						_messageHandler.post(job);
//					}
//				}.start();
//			}
//			catch (Exception e)
//			{
//				if (_messageHandler != null)
//					_messageHandler.post(job);
//				// e.printStackTrace();
//			}
//		}
//	}
	
//	private class MonitorAsyncTask extends BaseAsyncTask
//	{
//		private List<String[]> fields_list = new ArrayList<String[]>();
//		private Vector<MonitorViewHolder> _monitorLoadingList = new Vector<MonitorViewHolder>();
//		private boolean isSunflower = true;
//		
//		public MonitorAsyncTask(Context context)
//		{
//			super(context);
//		}
//		
//		private int retryCount = 0;
//		private int retryMaxCount = 3;
//		
//		public MonitorAsyncTask(Context context, boolean isSunflower)
//		{
//			super(context);
//			this.isSunflower = isSunflower;
//		}
//
//		@Override
//		protected void onPreExecute()
//		{
//			if(isSunflower)
//				super.onPreExecute();
//		}
//		
//
//		@Override
//		protected Void doInBackground(String... params)
//		{
//			List<String[]> items = _dbHelper.getSubscribeItemsByUserId(1);
//			if (items == null || items.size() < 1)
//				return null;
//
//			_isCustomerSubscribedItems = true;
////			_monitorList.clear();
//			_monitorLoadingList.clear();
//
//			StringBuffer stockItems = null; // stock
//
//			StringBuffer goldInfoItems = null; // gold
//			StringBuffer goldNames = null;
//
//			StringBuffer indexFuturesItems = null; // futures
//
//			StringBuffer indexItems = null; // index
//			StringBuffer indexNames = null;
//
//			/* "上証SSEI" by ouyangzhihui 2011-08-25 */
//			StringBuffer worldIndexDelayRealtimeItems = null;// worldIndexSSEI
//			StringBuffer worldIndexDelayRealtimeNames = null;
//
//			StringBuffer worldIndexItems = null; // wordIndexOther
//			StringBuffer worldIndexNames = null;
//
//			StringBuffer worldIndexFuturesItems = null; // worldFutures
//
//			StringBuffer worldIndexDelayItems = null; // worldIndex(深圳SZA，深圳SZB)
//			StringBuffer worldIndexDelayNames = null;
//
//			StringBuffer fxItems = null; // fx
//
//			boolean isSubscribedOil = false;
//			_listView.SetEditingMode(_isEditing);
//
//			for (final String[] array : items)
//			{
//				TDStockLog.d(TAG, "BMP=" + array[0] + " , " + array[1] + " , " + array[2] + " , " + array[3] + " , " + array[4] + " , " + array[5]);
//
//				MonitorViewHolder monitorViewHolder = new MonitorViewHolder();
//				monitorViewHolder.isEditable = _isEditing;
//				monitorViewHolder.isTop20orSector = false;
//				monitorViewHolder.adapter = array[1];
//				monitorViewHolder.itemCode = new TextView(BMPPortfolioActivity.this);
//				monitorViewHolder.itemCode.setText(array[0]);
//				monitorViewHolder.itemName = new TextView(BMPPortfolioActivity.this);
//				monitorViewHolder.itemValue = new TextView(BMPPortfolioActivity.this);
//				monitorViewHolder.itemNet = new TextView(BMPPortfolioActivity.this);
//				monitorViewHolder.itemNetPercentage = new TextView(BMPPortfolioActivity.this);
//
//				// deal with stock
//				if (TextUtils.isDigitsOnly(array[0]) && StockInfo.ADAPTER.equalsIgnoreCase(array[1]))
//				{
//					if (stockItems == null)
//					{
//						stockItems = new StringBuffer();
//						stockItems.append(array[0]);
//					}
//					else
//					{
//						stockItems.append(",").append(array[0]);
//					}
//				}
//				// deal with metal
//				else if (IntlMetalInfo.ADAPTER.equalsIgnoreCase(array[1]) && !ForeignExchangeInfo.CODE_TO_NAME.containsKey(array[0]))
//				{
//					if (goldInfoItems == null)
//					{
//						goldInfoItems = new StringBuffer();
//						goldInfoItems.append(array[0]);
//						goldNames = new StringBuffer();
//						goldNames.append(array[2]);
//					}
//					else
//					{
//						goldInfoItems.append(",").append(array[0]);
//						goldNames.append(",").append(array[2]);
//					}
//					monitorViewHolder.itemName.setText(array[2]);
//				}
//				// deal with index futures
//				else if (IndexFuturesInfo.ADAPTER.equalsIgnoreCase(array[1]))
//				{
//					if (indexFuturesItems == null)
//					{
//						indexFuturesItems = new StringBuffer(array[0]);
//					}
//					else
//					{
//						indexFuturesItems.append(",").append(array[0]);
//					}
//				}
//				// deal with index
//				else if (IndexInfo.ADAPTER.equalsIgnoreCase(array[1]))
//				{
//					array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");
//					if (indexItems == null)
//					{
//						indexItems = new StringBuffer(array[0]);
//						indexNames = new StringBuffer(array[2]);
//					}
//					else
//					{
//						indexItems.append(",").append(array[0]);
//						indexNames.append(",").append(array[2]);
//					}
//					monitorViewHolder.itemName.setText(array[2] == null ? "" : array[2]);
//				}
//				// deal with world index("上証SSEI")
//				/*--"上証SSEI"-----by ouyangzhihui 2011-08-25-----------*/
//				else if ((WorldIndexInfo.ADAPTER + WorldIndexDelayInfo.ADAPTER).equalsIgnoreCase(array[1]))
//				{
//					array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");
//
//					if (worldIndexDelayRealtimeItems == null)
//					{
//						worldIndexDelayRealtimeItems = new StringBuffer(array[0]);
//						worldIndexDelayRealtimeNames = new StringBuffer(array[2]);
//					}
//					else
//					{
//						worldIndexDelayRealtimeItems.append(",").append(array[0]);
//						worldIndexDelayRealtimeNames.append(",").append(array[2]);
//					}
//					monitorViewHolder.itemName.setText(array[2] == null ? "" : array[2]);
//				}
//				// deal with world index
//				else if (WorldIndexInfo.ADAPTER.equalsIgnoreCase(array[1]))
//				{
//					array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");
//					if (worldIndexItems == null)
//					{
//						worldIndexItems = new StringBuffer(array[0]);
//						worldIndexNames = new StringBuffer(array[2]);
//					}
//					else
//					{
//						worldIndexItems.append(",").append(array[0]);
//						worldIndexNames.append(",").append(array[2]);
//					}
//					monitorViewHolder.itemName.setText(array[2] == null ? "" : array[2]);
//				}
//				// deal with world index futures
//				else if (WorldFuturesInfo.ADAPTER.equalsIgnoreCase(array[1]))
//				{
//					array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");
//					if (worldIndexFuturesItems == null)
//					{
//						worldIndexFuturesItems = new StringBuffer(array[0]);
//					}
//					else
//					{
//						worldIndexFuturesItems.append(",").append(array[0]);
//					}
//				}
//				// deal with world index delay (深圳SZA，深圳SZB)
//				else if (WorldIndexDelayInfo.ADAPTER.equalsIgnoreCase(array[1]))
//				{
//					array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");
//					if (worldIndexDelayItems == null)
//					{
//						worldIndexDelayItems = new StringBuffer(array[0]);
//						worldIndexDelayNames = new StringBuffer(array[2].length() >= 5 ? array[2].substring(0, 5) : array[2]);
//					}
//					else
//					{
//						worldIndexDelayItems.append(",").append(array[0]);
//						worldIndexDelayNames.append(",").append(array[2].length() >= 5 ? array[2].substring(0, 5) : array[2]);
//					}
//					monitorViewHolder.itemName.setText(array[2].length() >= 5 ? array[2].substring(0, 5) : array[2]);
//				}
//				// deal with fx
//				else if (ForeignExchangeInfo.ADAPTER.equalsIgnoreCase(array[1]))
//				{
//					if (fxItems == null)
//					{
//						fxItems = new StringBuffer(array[0]);
//					}
//					else
//					{
//						fxItems.append(",").append(array[0]);
//					}
//				}
//				else if (OilInfo.ADAPTER.equalsIgnoreCase(array[1]))
//				{
//					isSubscribedOil = true;
//				}
//
//				_monitorLoadingList.add(monitorViewHolder);
////				_monitorList.add(monitorViewHolder);
//			}
//
//			try
//			{
//				Map<String, Stock> stockList = null;
//				Map<String, Index> indexList = null;
//				Map<String, Futures> futuresList = null;
//				Map<String, WorldFutures> worldFuturesList = null;
//				Map<String, WorldIndex> worldIndexList_ssei = null;
//				Map<String, WorldIndex> worldIndexList_other = null;
//				Map<String, WorldIndex> worldIndexList_delay = null; 
//				Map<String, Metal> metalList = null;
//				Map<String, Fx> fxList = null;
//				Oil	oil = null;
//				
//				if (goldInfoItems != null)
//				{
//					metalList = HttpDataBaseUtils.getDataByMetal_Monitor2(goldInfoItems.toString(), ((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
////					metalList = HttpDataBaseUtils.getDataByMetal_Monitor(goldInfoItems.toString().split("[,]"));
//				}
//				
//				if (stockItems != null) // stock
//				{
//					stockList = HttpDataBaseUtils.getDataByStock_Monitor2(stockItems.toString(), ((ITDLApplication)getApplicationContext()).getSessionAccount(),((ITDLApplication)getApplicationContext()).getSessionToken());
////					stockList = HttpDataBaseUtils.getDataByStock_Monitor(stockItems.toString().split("[,]"));
//				}
//
//				if (indexFuturesItems != null)
//				{
//					futuresList = HttpDataBaseUtils.getDataByFutures_Monitor2(
//							!((ITDLApplication) getApplicationContext()).getIsRealtimeFutures(),
//							indexFuturesItems.toString(), ((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
////					futuresList = HttpDataBaseUtils.getDataByFutures_Monitor(
////							((ITDLApplication) getApplicationContext()).getIsRealtimeFutures(),
////							indexFuturesItems.toString().split("[,]"));
//				}
//
//				if (indexItems != null)
//				{
//					indexList = HttpDataBaseUtils.getDataByIndex_Monitor2(indexItems.toString(), ((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
////					indexList = HttpDataBaseUtils.getDataByIndex_Monitor(indexItems.toString().split("[,]"));
//				}
//				/*--"上証SSEI"-----by ouyangzhihui 2011-08-25-----------*/
//				if (worldIndexDelayRealtimeItems != null)
//				{
//					worldIndexList_ssei = HttpDataBaseUtils.getDataByWorldIndexSSEI_Monitor2(
//							!((ITDLApplication) getApplicationContext()).getIsRealtimeSSEI(),
//							worldIndexDelayRealtimeItems.toString(), ((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
////					worldIndexList_ssei = HttpDataBaseUtils.getDataByWorldIndexSSEI_Monitor(
////							((ITDLApplication) getApplicationContext()).getIsRealtimeSSEI(),
////							worldIndexDelayRealtimeItems.toString().split(","));
//				}
//				/*-------by ouyangzhihui 2011-08-25-----------*/
//				if (worldIndexItems != null)
//				{
//					worldIndexList_other = HttpDataBaseUtils.getDataByWorldIndexOther_Monitor2(worldIndexItems.toString(), ((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
////					worldIndexList_other = HttpDataBaseUtils.getDataByWorldIndexOther_Monitor(worldIndexItems.toString().split("[,]"));
//				}
//
//				if (worldIndexFuturesItems != null)
//				{
//					worldFuturesList = HttpDataBaseUtils.getDataByWorldFutures_Monitor2(worldIndexFuturesItems.toString(), ((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
////					worldFuturesList = HttpDataBaseUtils.getDataByWorldFutures_Monitor(worldIndexFuturesItems.toString().split("[,]"));
//				}
//
//				if (worldIndexDelayItems != null)
//				{
//					worldIndexList_delay = HttpDataBaseUtils.getDataByWorldIndexOther_Monitor2(worldIndexDelayItems.toString(), ((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
////					worldIndexList_delay = HttpDataBaseUtils.getDataByWorldIndexOther_Monitor(worldIndexDelayItems.toString().split("[,]"));
//				}
//
//				if (fxItems != null)
//				{
//					fxList = HttpDataBaseUtils.getDataByFx_Monitor2(fxItems.toString(), ((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
////					fxList = HttpDataBaseUtils.getDataByFx_Monitor(fxItems.toString().split("[,]"));
//				}
//
//				if (isSubscribedOil)
//				{
//					oil = HttpDataBaseUtils.getDataByOil_Monitor(((ITDLApplication)getApplicationContext()).getSessionAccount(), ((ITDLApplication)getApplicationContext()).getSessionToken());
//				}
//				
//				/*----------Update Adapter---------*/
//				
//				// stock
//				if(stockList != null)
//				{
//					for (int i = 0; i < stockList.size(); i++)
//					{
//						String[]fields = OnUpdateStock(stockList.get(stockItems.toString().split("[,]")[i]));
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//				// index 
//				if(indexList != null)
//				{
//					for (int i = 0; i < indexList.size(); i++)
//					{
//						Index index = indexList.get(indexItems.toString().split("[,]")[i]);
//						String[]fields = OnUpdateIndex(i, index.getName(), index, indexNames.toString().split("[,]"), IndexInfo.ADAPTER);
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//				// futures
//				if(futuresList != null)
//				{
//					for (int i = 0; i < futuresList.size(); i++)
//					{
//						Futures futures = futuresList.get(indexFuturesItems.toString().split(",")[i]);
//						String[]fields = OnUpdateFutures(futures.getName(), futures);
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//				// worldFutures
//				if(worldFuturesList != null)
//				{
//					for (int i = 0; i < worldFuturesList.size(); i++)
//					{
//						WorldFutures worldFutures = worldFuturesList.get(worldIndexFuturesItems.toString().split("[,]")[i]);
//						String[]fields = OnUpdateFutures(worldFutures.getName(), worldFutures);
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//				// worldIndex ssei
//				if(worldIndexList_ssei != null)
//				{
//					String adapter = ((ITDLApplication) getApplicationContext()).getIsRealtimeSSEI() ? WorldIndexInfo.ADAPTER : WorldIndexDelayInfo.ADAPTER;
//					for (int i = 0; i < worldIndexList_ssei.size(); i++)
//					{
//						WorldIndex worldIndex = worldIndexList_ssei.get(worldIndexDelayRealtimeItems.toString().split("[,]")[i]);
//						String[]fields = OnUpdateIndex(i, worldIndex.getName(), worldIndex, worldIndexDelayRealtimeNames.toString().split("[,]"), adapter, "true");
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//				// worldIndex other
//				if(worldIndexList_other != null)
//				{
//					for (int i = 0; i < worldIndexList_other.size(); i++)
//					{
//						WorldIndex worldIndex = worldIndexList_other.get(worldIndexItems.toString().split("[,]")[i]);
//						String[]fields = OnUpdateIndex(i, worldIndex.getName(), worldIndex, worldIndexNames.toString().split("[,]"), WorldIndexInfo.ADAPTER);
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//				// worldIndex delay(深圳SZA，深圳SZB)
//				if(worldIndexList_delay != null)
//				{
//					for (int i = 0; i < worldIndexList_delay.size(); i++)
//					{
//						WorldIndex worldIndex = worldIndexList_delay.get(worldIndexDelayItems.toString().split("[,]")[i]);
//						String[]fields = OnUpdateIndex(i, worldIndex.getName(), worldIndex, worldIndexDelayNames.toString().split("[,]"), WorldIndexDelayInfo.ADAPTER);
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//				// metal
//				if(metalList != null)
//				{
//					for (int i = 0; i < metalList.size(); i++)
//					{
//						String[]fields = OnUpdateGold(i, metalList.get(goldInfoItems.toString().split("[,]")[i]), goldNames.toString().split("[,]"));
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//				// fx
//				if(fxList != null)
//				{
//					for (int i = 0; i < fxList.size(); i++)
//					{
//						String[]fields = OnUpdateFx(fxList.get(fxItems.toString().split("[,]")[i]));
//						if(fields != null)
//							fields_list.add(fields);
//					}
//				}
//				// oil
//				if(oil != null)
//				{
//					String[] fields = OnUpdateOil(oil);
//					if(fields != null)
//						fields_list.add(fields);
//				}
//				retryCount = 0;
//			}
//			catch (Exception e)
//			{
//				TDStockLog.d(TAG, "exception = doInBackground > " + TAG + e.toString() + " , " + retryCount);
//				
//				if(retryCount++ < retryMaxCount)
//					new MonitorAsyncTask(getMyOwnContext(), true);
//				
//				if(monitorAsyncTask != null)
//				{
//					monitorAsyncTask.cancel(true);
//					monitorAsyncTask = null;
//				}
//				else
//					cancel(true);
//				
//				e.printStackTrace();
//			}
//			return super.doInBackground(params);
//		}
//
//		@Override
//		protected void onPostExecute(Void result)
//		{
//			if(retryCount > 0 && monitorAsyncTask == null) return;
//			
//			_monitorList.clear();
//			for(MonitorViewHolder viewHolder : _monitorLoadingList)
//			{
//				_monitorList.add(viewHolder);
//			}
//			_monitorLoadingList.clear();
//			
//			TDStockLog.d(TAG, "exception = onPostExecute > " + TAG + " , size=" + _monitorList.size());
//			
//			if(isSunflower)
//				super.onPostExecute(result);
//			
//			GetTimeData();
//			
//			// update adapter
//			for(int i = 0; i < fields_list.size(); i++)
//			{
//				updateAdapter(fields_list.get(i));
//			}
//			
//			_listView.setClickable(false);
//			_monitor_item_Adapter.notifyDataSetChanged();
//			_listView.setClickable(true);
//			
//			monitorAsyncTask = null;
//		}
//	}
	
	private void GetTimeData()
	{
		final Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					HttpAppInfo.SendBMPTimeRequest(actContext, new IH_UserClient_HttpRequest_Report()
					{
						@Override
						public void H_UserClient_HttpRequest_Response(H_UserClient_HttpRequest_Result iResult)
						{
							if(!iResult.MStatus.equals("0"))
								return;
							if(iResult.contentStores.size() <= 0)
								return;
							
							String serverTime = iResult.contentStores.get(0)[0];
							
							if(serverTime != null && serverTime.length() > 1)
							{
								serverTime = serverTime.substring(8, 10) + ":" + serverTime.substring(10, 12) + ":" + serverTime.substring(12, 14); 
							}
							syncServerTimer(serverTime);
						}
					});
					
//					String serverTime = HttpDataBaseUtils.getDataByTime();
//					if(serverTime.length() > 1)
//					{
//						serverTime = serverTime.substring(8, 10) + ":" + serverTime.substring(10, 12) + ":" + serverTime.substring(12, 14); 
//					}
//					syncServerTimer(serverTime);
				}
				catch(Exception e)
				{
					TDStockLog.d(TAG, "exception = serverTime " + TAG + e.toString());
				}
			}
		};
		new Thread()
		{
			@Override
			public void run()
			{
				_messageHandler.post(runnable);
			}
		}.start();
	}
	
	public synchronized void syncServerTimer(String time)
	{
		try
		{
			if (time != null && !"".equals(time))
			{
				_last_update_time.setText(time.length() >= 8 ? time.subSequence(0, 8) : time);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public String[] OnUpdateFutures(final String itemName, final Object update)
	{
		try
		{
			// do nothing for the monitor is editing.
			if (_isEditing || !isItemExist(itemName))
				return null;
	
			String _adapter;
			_adapter = IndexFuturesInfo.ADAPTER; 
	
			final String[] fields = new String[6];
			if (itemName.matches("HSI:[0-9]"))
			{
				Futures futures = (Futures) update;
				
				String mm = futures.getMm();
				fields[0] = String.format("恆指%s月", mm != null ? Integer.parseInt(mm) : CommonDefn.DEFAULT_FIELD_VALUE);
				if (!((ITDLApplication) getApplicationContext()).getIsRealtimeFutures())
				{
					fields[0] = fields[0] + "*";
				}
				fields[1] = StringUtils.roundDownInteger(futures.getLast());
				fields[2] = StringUtils.formatToFiveCharsRule(futures.getNet());
	//			fields[3] = futures.getNetPercentage();
				fields[3] = StringUtils.formatRoundUpByNetPercetageNumber(Double.parseDouble(futures.getNet()) / Double.parseDouble(futures.getPrev()) * 100);
				fields[3] = (fields[3] != null && !"".equals(fields[3])) ? (StringUtils.formatToFiveCharsRule(fields[3]) + "%") : CommonDefn.DEFAULT_FIELD_VALUE;
				//_adapter = IndexFuturesInfo.ADAPTER;
				_adapter = IndexFuturesInfo.adapter_realtime;
			}
			else if (itemName.matches("HHI:[0-9]"))
			{
				Futures futures = (Futures) update;
				
				String mm = futures.getMm();
				fields[0] = String.format("國企%s月", mm != null ? Integer.parseInt(mm) : CommonDefn.DEFAULT_FIELD_VALUE);
				if (!((ITDLApplication) getApplicationContext()).getIsRealtimeFutures())
				{
					fields[0] = fields[0] + "*";
				}
				fields[1] = StringUtils.roundDownInteger(futures.getLast());
				fields[2] = StringUtils.formatToFiveCharsRule(futures.getNet());
	//			fields[3] = futures.getNetPercentage();
				fields[3] = StringUtils.formatRoundUpByNetPercetageNumber(Double.parseDouble(futures.getNet()) / Double.parseDouble(futures.getPrev()) * 100);
				fields[3] = (fields[3] != null && !"".equals(fields[3])) ? (StringUtils.formatToFiveCharsRule(fields[3]) + "%") : CommonDefn.DEFAULT_FIELD_VALUE;
				//_adapter = IndexFuturesInfo.ADAPTER;
				_adapter = IndexFuturesInfo.adapter_realtime;
			}
			else if (itemName.matches("SSI:[0-9]"))
			{
				WorldFutures worldFutures = (WorldFutures) update;
	
				String mm = worldFutures.getMm();
				fields[0] = String.format("日經%s月", mm != null ? Integer.parseInt(mm) : CommonDefn.DEFAULT_FIELD_VALUE);
				fields[1] = StringUtils.roundDownInteger(worldFutures.getLast());
				fields[2] = StringUtils.formatToFiveCharsRule(worldFutures.getNet());
				fields[3] = CommonDefn.DEFAULT_FIELD_VALUE;
				_adapter = WorldFuturesInfo.ADAPTER;
			}
			else if (itemName.matches("DJI:[0-9]"))
			{
				WorldFutures worldFutures = (WorldFutures) update;
	
				String mm = worldFutures.getMm();
				fields[0] = String.format("道指%s月", mm != null ? Integer.parseInt(mm) : CommonDefn.DEFAULT_FIELD_VALUE);
				fields[1] = StringUtils.roundDownInteger(worldFutures.getLast());
				fields[2] = StringUtils.formatToFiveCharsRule(worldFutures.getNet());
				fields[3] = CommonDefn.DEFAULT_FIELD_VALUE;
				_adapter = WorldFuturesInfo.ADAPTER;
			}
			
			fields[4] = itemName;
			fields[5] = _adapter;
			
			return fields;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	public String[] OnUpdateFuturesCOP(final String itemName, final Object update)
	{
		try
		{
			// do nothing for the monitor is editing.
			if (_isEditing || !isItemExist(itemName))
				return null;
	
			String _adapter = IndexFuturesInfo.ADAPTER + IndexFuturesInfo.COP;
	
			final String[] fields = new String[6];
			
			Futures futures = (Futures) update;
			String mm = futures.getMm();
			
			if (itemName.matches("HSI:[0-9]"))
			{
				fields[0] = String.format("恆%s月C", mm != null ? Integer.parseInt(mm) : CommonDefn.DEFAULT_FIELD_VALUE);
			}
			else if (itemName.matches("HHI:[0-9]"))
			{
				fields[0] = String.format("國%s月C", mm != null ? Integer.parseInt(mm) : CommonDefn.DEFAULT_FIELD_VALUE);
			}
			
			fields[1] = StringUtils.roundDownInteger(futures.getCop());
			fields[2] = CommonDefn.DEFAULT_FIELD_VALUE;
			fields[3] = CommonDefn.DEFAULT_FIELD_VALUE;
			
			fields[4] = itemName;
			fields[5] = _adapter;
			
			return fields;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public String[] OnUpdateIndex(final int itemPos, final String itemName, final Object update, String[] itemNames, String adapter, String... isSSEI)
	{
		try
		{
			// do nothing for the monitor is editing.
			if (_isEditing || !isItemExist(itemName))
				return null;
	
			boolean _isSSEI;
			String[] _itemNames;
			final String _adapter;
	
			if (isSSEI.length > 0)
				_isSSEI = true;
			else _isSSEI = false;
	
			_itemNames = itemNames;
			_adapter = adapter;
	
			final String[] fields = new String[6];
	
			fields[0] = _itemNames[itemPos];
			if (_isSSEI && !((ITDLApplication) getApplicationContext()).getIsRealtimeSSEI())
			{
				fields[0] = fields[0] + "*";
			}
			/*
			 * if(fields[0].endsWith("(延遲)")) { fields[0] = fields[0].substring(0,
			 * fields[0].length()-4); } else
			 */if (StringUtils.EN_CHARS.contains(fields[0].substring(fields[0].length() - 1, fields[0].length())))
			{
				fields[0] = fields[0].substring(0, 5);
			}
			if (_adapter.equals(IndexInfo.ADAPTER))
			{
				Index index = (Index) update;
	
				fields[1] = StringUtils.roundDownInteger(index.getLast());
				fields[2] = StringUtils.formatToFiveCharsRule(index.getNet());
	//			fields[3] = index.getNetPercentage();
				fields[3] = StringUtils.formatRoundUpByNetPercetageNumber(Double.parseDouble(index.getNet()) / Double.parseDouble(index.getPrev()) * 100);
				fields[3] = (fields[3] != null && !"".equals(fields[3])) ? StringUtils.formatToFiveCharsRule(fields[3]) + "%" : CommonDefn.DEFAULT_FIELD_VALUE;
			}
			else if (_adapter.equals(WorldIndexInfo.ADAPTER) || _adapter.equals(WorldIndexDelayInfo.ADAPTER))
			{
				WorldIndex worldIndex = (WorldIndex) update;
	
				fields[1] = StringUtils.roundDownInteger(worldIndex.getLast());
				fields[2] = StringUtils.formatToFiveCharsRule(worldIndex.getNet());
	//			fields[3] = worldIndex.getNetPercentage();
				fields[3] = StringUtils.formatRoundUpByNetPercetageNumber(Double.parseDouble(worldIndex.getNet()) / Double.parseDouble(worldIndex.getPrev()) * 100);
				fields[3] = (fields[3] != null && !"".equals(fields[3])) ? StringUtils.formatToFiveCharsRule(fields[3]) + "%" : CommonDefn.DEFAULT_FIELD_VALUE;
			}
	
			fields[4] = itemName;
			fields[5] = _adapter;
			
			return fields;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public String[] OnUpdateFx(final Fx update)
	{
		try
		{
			// do nothing for the monitor is editing.
			if (_isEditing || !isItemExist(update.getName()))
				return null;
	
			NumberFormat _formater;
			_formater = DecimalFormat.getInstance();
			_formater.setMaximumFractionDigits(4);
			_formater.setMinimumFractionDigits(4);
			_formater.setGroupingUsed(false);
	
			final String[] fields = new String[6];
			fields[0] = ForeignExchangeInfo.CODE_TO_NAME.get(update.getName());
	
			try
			{
				Double bid = Double.parseDouble(update.getBid());
				Double ask = Double.parseDouble(update.getAsk());
	
				fields[1] = _formater.format((bid + ask) / 2);
				while (fields[1].endsWith("0"))
				{
					fields[1] = fields[1].substring(0, fields[1].length() - 1);
				}
	
				if (fields[1].length() > 6)
				{
					fields[1] = fields[1].substring(0, 6);
				}
			}
			catch (NumberFormatException e)
			{
				fields[1] = CommonDefn.DEFAULT_FIELD_VALUE2;
			}
	
			fields[2] = update.getNet();
			fields[3] = update.getNetPercentage();
			fields[3] = StringUtils.formatNumberByNetPerectage(fields[3], 4);
	
			fields[4] = update.getName();
			fields[5] = ForeignExchangeInfo.ADAPTER;
			
			return fields;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	
	 public String[] OnUpdateOil(final Oil update) 
	 {
		 try
		 {
			 //do nothing for the monitor is editing. 
			 if (_isEditing || update == null || !isItemExist(update.getName())) 
				 return null; 
			 final String[] fields = new String[6];
			 fields[0] = OilInfo.SUBSCRIBE_ITEMS_NAME_4_MONITOR[0]; 
			 fields[1] = update.getLast();
			 fields[2] = update.getNet();
			 try 
			 { 
				 double now = Double.parseDouble(fields[1]);
				 double net = Double.parseDouble(fields[2]); 
				 double netPercentage = ((now) / (now - net) - 1) * 100.00d;
				 fields[3] = StringUtils.FormatNumber(StringUtils.ITDLNumber.NETPERCENTAGE, String.valueOf(netPercentage)); 
			 }
			 catch (Exception e) 
			 { 
			 }
			 
			 fields[4] = update.getName();
			 fields[5] = OilInfo.ADAPTER;
			 
			 return fields;
		 }
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public String[] OnUpdateStock(final Stock update)
	{
		try
		{
			if (_isEditing || !isItemExist(update.getStock_code()))
				return null;
	
			// Update content
			final String[] fields = new String[6];
			fields[0] = update.getSchi_name();
	
			fields[1] = StringUtils.roundDownFormatToFiveCharsRule(update.getNominal());
			fields[2] = StringUtils.formatNumberByNet(update.getNet());
	//		fields[3] = update.getNetPercentage();
			fields[3] = StringUtils.formatRoundUpByNetPercetageNumber(Double.parseDouble(update.getNet()) / Double.parseDouble(update.getPrev_close_price()) * 100);
			int p = 4;
			try
			{
				if (Double.parseDouble(fields[3]) > 10)
					p = 5;
			}
			catch (Exception e)
			{
			}
			fields[3] = StringUtils.formatNumberByNetPerectage(fields[3], p);
			
			fields[4] = update.getStock_code();
			fields[5] = StockInfo.ADAPTER;
			return fields;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public String[] OnUpdateGold(final int itemPos, final Metal update, String[] itemNames)
	{
		try
		{
			if (_isEditing || !isItemExist(update.getName()))
				return null;
	
			String[] _itemNames;
			_itemNames = itemNames;
	
			final String[] fields = new String[6];
			fields[0] = _itemNames[itemPos];
			fields[1] = StringUtils.roundDownFormatToSixCharsRule(update.getLast());
			fields[2] = CommonDefn.DEFAULT_FIELD_VALUE;
			fields[3] = CommonDefn.DEFAULT_FIELD_VALUE;
			
			fields[4] = update.getName();
			fields[5] = IntlMetalInfo.ADAPTER;
	
			return fields;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	private void updateDataByStockSector(List<Stock> stockList, String[] stockCodes)
	{
		try
		{
			List<String[]> fields_list = new ArrayList<String[]>();
			// Sector List update
			for (int i = 0; i < stockList.size(); i++)
			{
				String[] fields = OnUpdateStock(stockList.get(i));
				if(fields != null)
					fields_list.add(fields);
			}
			
			_monitorList.clear();
			for (final String stk : stockCodes)
			{
				MonitorViewHolder monitorViewHolder = new MonitorViewHolder();
				monitorViewHolder.isEditable = _isEditing;
				monitorViewHolder.adapter = StockInfo.ADAPTER;
				monitorViewHolder.isTop20orSector = true;
				monitorViewHolder.itemCode = new TextView(BMPPortfolioActivity.this);
				monitorViewHolder.itemCode.setText(stk);
				monitorViewHolder.itemName = new TextView(BMPPortfolioActivity.this);
				monitorViewHolder.itemValue = new TextView(BMPPortfolioActivity.this);
				monitorViewHolder.itemNet = new TextView(BMPPortfolioActivity.this);
				monitorViewHolder.itemNetPercentage = new TextView(BMPPortfolioActivity.this);
	
				_monitorList.add(monitorViewHolder);
			}
			
			for(int i = 0; i < fields_list.size(); i++)
			{
				updateAdapter(fields_list.get(i));
			}
			
			progressView.DismissProgress();
			
			_listView.setClickable(false);
			_monitor_item_Adapter.notifyDataSetChanged();
			_listView.setClickable(true);
			
			GetTimeData();
			
			_monitor_item_Adapter.notifyDataSetChanged();
		}
		catch(Exception e)
		{
			progressView.DismissProgress();
			e.printStackTrace();
		}
	}
	
	private void SendHttpRequestBySector(String iTypeName)
	{
		H_CODE statusCode;
		statusCode = HttpAppInfo.SendStockSectorRequest(actContext, iTypeName, new IH_UserClient_HttpRequest_Report()
		{
			@Override
			public void H_UserClient_HttpRequest_Response(H_UserClient_HttpRequest_Result iResult)
			{
				if(iHConnectIsDestory)
				{
					progressView.DismissProgress();
					return;
				}
				if(!iResult.MStatus.equals("0"))
				{
					progressView.DismissProgress();
					ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
					return;
				}
				
				List<String[]> arrTmp = iResult.contentStores;
				String[] stockCodes = new String[arrTmp.size()];
				
				for(int index = 0; index < arrTmp.size(); index++)
				{
					stockCodes[index] = arrTmp.get(index)[0];
				}
				sortAsNumbersByAsc(stockCodes);
				
				String stockCodeString = "";
				for(int index = 0; index < arrTmp.size(); index++)
				{
					stockCodeString += stockCodes[index];
					if(index < arrTmp.size())
						 stockCodeString +=  ",";
				}
				
				if(stockCodeString.length() <= 0) 
					return;
				
				final String[] _stockCodes = stockCodes;
				
				H_CODE h_code;
				h_code = HttpAppInfo.SendStockSectorMonitorRequest(actContext, stockCodeString, new IH_UserClient_HttpRequest_Report()
				{
					@Override
					public void H_UserClient_HttpRequest_Response(H_UserClient_HttpRequest_Result iResult)
					{
						if(iHConnectIsDestory)
						{
							progressView.DismissProgress();
							return;
						}
						if(!iResult.MStatus.equals("0"))
						{
							progressView.DismissProgress();
							ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
							return;
						}
						
						if(iResult.objListStores.size() <= 0)
						{
							progressView.DismissProgress();
							return;
						}
						
						final List<Stock> stockList = (List<Stock>) iResult.objListStores; 
						final Runnable runnable = new Runnable()
						{
							@Override
							public void run()
							{
								updateDataByStockSector(stockList, _stockCodes);
							}
						};
						new Thread()
						{
							@Override
							public void run()
							{
								_messageHandler.post(runnable);
							}
						}.start();
					}
				});
				
				if(h_code == null || h_code == H_CODE.NONE)
					return;
				if (h_code != H_CODE.OK && h_code != H_CODE.SYSTEM_BUSY)
				{
					ShowMessageDialog(h_code.ToString());
				}
			}
		});
		ShowHideDialog(statusCode);
	}
	
	private List<MonitorViewHolder> _monitorLoadingList = new ArrayList<MonitorViewHolder>();
	
	private StringBuffer[] itemNames; 
	
	/**
	 * [0]  stockItems <br/>
	 * [1]  goldInfoItems <br/>
	 * [2]  goldNames <br/>
	 * [3]  indexFuturesItems <br/>
	 * [4]  indexItems <br/>
	 * [5]  indexNames <br/>
	 * [6]  worldIndexDelayRealtimeItems <br/>
	 * [7]  worldIndexDelayRealtimeNames <br/>
	 * [8]  worldIndexItems <br/>
	 * [9]  worldIndexNames <br/>
	 * [10] worldIndexFuturesItems <br/>
	 * [11] worldIndexDelayItems <br/>
	 * [12] worldIndexDelayNames <br/>
	 * [13] fxItems <br/>
	 * [14] isSubscribedOil <br/>
	 * @return
	 */
	private StringBuffer[] InitItemNames()
	{
		List<String[]> items = /*_dbHelper.getSubscribeItemsByUserId(1);*/ _monitorItemFromServer;
		if (items == null || items.size() < 1)
			return null;

		_isCustomerSubscribedItems = true;
		_monitorLoadingList.clear();

		StringBuffer stockItems = null; // stock

		StringBuffer goldInfoItems = null; // gold
		StringBuffer goldNames = null;

		StringBuffer indexFuturesItems = null; // futures
		StringBuffer indexFuturesCOPItems = null; // futures Cop

		StringBuffer indexItems = null; // index
		StringBuffer indexNames = null;

		/* "上証SSEI" by ouyangzhihui 2011-08-25 */
		StringBuffer worldIndexDelayRealtimeItems = null;// worldIndexSSEI
		StringBuffer worldIndexDelayRealtimeNames = null;

		StringBuffer worldIndexItems = null; // wordIndexOther
		StringBuffer worldIndexNames = null;

		StringBuffer worldIndexFuturesItems = null; // worldFutures

		StringBuffer worldIndexDelayItems = null; // worldIndex(深圳SZA，深圳SZB)
		StringBuffer worldIndexDelayNames = null;

		StringBuffer fxItems = null; // fx
		
		StringBuffer isSubscribedOil = new StringBuffer("false");
		
		_listView.SetEditingMode(_isEditing);
		
		BookMarkUtil bm = BookMarkUtil.getInstance(BMPPortfolioActivity.this);

		for (final String[] array : items)
		{
			/*TDStockLog.d(TAG, "BMP=" + array[0] + " , " + array[1] + " , " + array[2] + " , " + array[3] + " , " + array[4] + " , " + array[5]);*/
			TDStockLog.d(TAG, "BMP=" + array[0] + " , " + array[1]);

			MonitorViewHolder monitorViewHolder = new MonitorViewHolder();
			monitorViewHolder.isEditable = _isEditing;
			monitorViewHolder.isTop20orSector = false;
			monitorViewHolder.type =  Integer.parseInt(array[1]);
			monitorViewHolder.isCop =  COP_TAG.equals(array[1]);
			monitorViewHolder.adapter = /*array[1];*/ monitorViewHolder.adapter = monitorViewHolder.isCop?    (IndexFuturesInfo.ADAPTER + IndexFuturesInfo.COP) :  bm.getItemRecord(array[0]).itemAdapter;
			monitorViewHolder.itemCode = new TextView(BMPPortfolioActivity.this);
			monitorViewHolder.itemCode.setText(array[0]);
			monitorViewHolder.itemName = new TextView(BMPPortfolioActivity.this);
			monitorViewHolder.itemValue = new TextView(BMPPortfolioActivity.this);
			monitorViewHolder.itemNet = new TextView(BMPPortfolioActivity.this);
			monitorViewHolder.itemNetPercentage = new TextView(BMPPortfolioActivity.this);

			// deal with stock
			if (TextUtils.isDigitsOnly(array[0]) && StockInfo.ADAPTER.equalsIgnoreCase(monitorViewHolder.adapter))
			{
				if (stockItems == null)
				{
					stockItems = new StringBuffer();
					stockItems.append(array[0]);
				}
				else
				{
					stockItems.append(",").append(array[0]);
				}
			}
			// deal with metal
			else if (IntlMetalInfo.ADAPTER.equalsIgnoreCase(monitorViewHolder.adapter) && !ForeignExchangeInfo.CODE_TO_NAME.containsKey(array[0]))
			{
				if (goldInfoItems == null)
				{
					goldInfoItems = new StringBuffer();
					goldInfoItems.append(array[0]);
					goldNames = new StringBuffer();
					goldNames.append( bm.getItemRecord(array[0]).itemName);
				}
				else
				{
					goldInfoItems.append(",").append(array[0]);
					goldNames.append(",").append( bm.getItemRecord(array[0]).itemName);
				}
				monitorViewHolder.itemName.setText( bm.getItemRecord(array[0]).itemName);
			}
			// deal with index futures
			else if (IndexFuturesInfo.adapter_realtime.equalsIgnoreCase(monitorViewHolder.adapter))
			{
				if (indexFuturesItems == null)
				{
					indexFuturesItems = new StringBuffer(array[0]);
				}
				else
				{
					indexFuturesItems.append(",").append(array[0]);
				}
			}
			// deal with index futures cop
			else if ((IndexFuturesInfo.ADAPTER + IndexFuturesInfo.COP).equalsIgnoreCase(monitorViewHolder.adapter))
			{
				if (indexFuturesCOPItems == null)
				{
					indexFuturesCOPItems = new StringBuffer(array[0]);
				}
				else
				{
					indexFuturesCOPItems.append(",").append(array[0]);
				}
			}
			// deal with index
			else if (IndexInfo.ADAPTER.equalsIgnoreCase(monitorViewHolder.adapter))
			{
				
				String itemName;
				try
				{
					// itemName =
					// BookMarkUtil.getInstance(PortfolioActivity.this).getItemName(array[0]);
					itemName = bm.getItemRecord(array[0]).itemName;
				}
				catch (Exception e)
				{
					itemName = CommonDefn.DEFAULT_FIELD_VALUE;
				}
				
				//array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");
				if (indexItems == null)
				{
					indexItems = new StringBuffer(array[0]);
					indexNames = new StringBuffer(itemName);
				}
				else
				{
					indexItems.append(",").append(array[0]);
					indexNames.append(",").append(itemName);
				}
				monitorViewHolder.itemName.setText(itemName);
			}
			// deal with world index("上証SSEI")
			/*--"上証SSEI"-----by ouyangzhihui 2011-08-25-----------*/
			else if ((WorldIndexInfo.ADAPTER + WorldIndexDelayInfo.ADAPTER).equalsIgnoreCase(monitorViewHolder.adapter))
			{
				/*array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");*/
				
				String itemName;
				try
				{
					// itemName =
					// BookMarkUtil.getInstance(PortfolioActivity.this).getItemName(array[0]);
					itemName = bm.getItemRecord(array[0]).itemName;
				}
				catch (Exception e)
				{
					itemName = CommonDefn.DEFAULT_FIELD_VALUE;
				}

				if (worldIndexDelayRealtimeItems == null)
				{
					worldIndexDelayRealtimeItems = new StringBuffer(array[0]);
					worldIndexDelayRealtimeNames = new StringBuffer(itemName);
				}
				else
				{
					worldIndexDelayRealtimeItems.append(",").append(array[0]);
					worldIndexDelayRealtimeNames.append(",").append(itemName);
				}
				monitorViewHolder.itemName.setText(itemName);
			}
			// deal with world index
			else if (WorldIndexInfo.ADAPTER.equalsIgnoreCase(monitorViewHolder.adapter))
			{
				//array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");
				
				String itemName;
				try
				{
					// itemName =
					// BookMarkUtil.getInstance(PortfolioActivity.this).getItemName(array[0]);
					itemName = bm.getItemRecord(array[0]).itemName;
				}
				catch (Exception e)
				{
					itemName = CommonDefn.DEFAULT_FIELD_VALUE;
				}
				
				
				if (worldIndexItems == null)
				{
					worldIndexItems = new StringBuffer(array[0]);
					worldIndexNames = new StringBuffer(itemName);
				}
				else
				{
					worldIndexItems.append(",").append(array[0]);
					worldIndexNames.append(",").append(itemName);
				}
				monitorViewHolder.itemName.setText(itemName);
			}
			// deal with world index futures
			else if (WorldFuturesInfo.ADAPTER.equalsIgnoreCase(monitorViewHolder.adapter))
			{
				//array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");
			
				if (worldIndexFuturesItems == null)
				{
					worldIndexFuturesItems = new StringBuffer(array[0]);
				}
				else
				{
					worldIndexFuturesItems.append(",").append(array[0]);
				}
			}
			// deal with world index delay (深圳SZA，深圳SZB)
			else if (WorldIndexDelayInfo.ADAPTER.equalsIgnoreCase(monitorViewHolder.adapter))
			{
				//array[2] = array[2].replaceAll("[\n\r]", "").replaceAll("(<br>)|(<BR>)", "").replace("(延遲)", "");
				String itemName;
				try
				{
					// itemName =
					// BookMarkUtil.getInstance(PortfolioActivity.this).getItemName(array[0]);
					itemName = bm.getItemRecord(array[0]).itemName;
				}
				catch (Exception e)
				{
					itemName = CommonDefn.DEFAULT_FIELD_VALUE;
				}
				if (worldIndexDelayItems == null)
				{
					worldIndexDelayItems = new StringBuffer(array[0]);
					worldIndexDelayNames = new StringBuffer(itemName.length() >= 5 ? itemName.substring(0, 5) : itemName);
				}
				else
				{
					worldIndexDelayItems.append(",").append(array[0]);
					worldIndexDelayNames.append(",").append(itemName.length() >= 5 ? itemName.substring(0, 5) : itemName);
				}
				monitorViewHolder.itemName.setText(itemName.length() >= 5 ? itemName.substring(0, 5) : itemName);
			}
			// deal with fx
			else if (ForeignExchangeInfo.ADAPTER.equalsIgnoreCase(monitorViewHolder.adapter))
			{
				if (fxItems == null)
				{
					fxItems = new StringBuffer(array[0]);
				}
				else
				{
					fxItems.append(",").append(array[0]);
				}
			}
			else if (OilInfo.ADAPTER.equalsIgnoreCase(monitorViewHolder.adapter))
			{
//				isSubscribedOil = true;
				isSubscribedOil = new StringBuffer("true");
			}

			_monitorLoadingList.add(monitorViewHolder);
			
		}
		StringBuffer[] itemNamesArray = 
		{
			stockItems, goldInfoItems, goldNames, indexFuturesItems, indexItems, indexNames, worldIndexDelayRealtimeItems, worldIndexDelayRealtimeNames,
			worldIndexItems, worldIndexNames, worldIndexFuturesItems, worldIndexDelayItems, worldIndexDelayNames, fxItems,
			isSubscribedOil, indexFuturesCOPItems
		};
		return itemNamesArray;
	}
	
	private int requestCount;
	
	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		itemNames = InitItemNames();
//		for(int i = 0; i < itemNames.length; i++)
//		{
//			TDStockLog.d(TAG, "ItemNams[" + i + "]:" + itemNames[i]);
//		}
		if(itemNames==null){
			return H_CODE.NONE;
		}
		
		StringBuffer stockItems = itemNames[0]; // stock

		StringBuffer goldInfoItems = itemNames[1]; // gold
		StringBuffer goldNames = itemNames[2];

		StringBuffer indexFuturesItems = itemNames[3]; // futures

		StringBuffer indexItems = itemNames[4]; // index
		StringBuffer indexNames = itemNames[5];

		/* "上証SSEI" by ouyangzhihui 2011-08-25 */
		StringBuffer worldIndexDelayRealtimeItems = itemNames[6];// worldIndexSSEI
		StringBuffer worldIndexDelayRealtimeNames = itemNames[7];

		StringBuffer worldIndexItems = itemNames[8]; // wordIndexOther
		StringBuffer worldIndexNames = itemNames[9];

		StringBuffer worldIndexFuturesItems = itemNames[10]; // worldFutures

		StringBuffer worldIndexDelayItems = itemNames[11]; // worldIndex(深圳SZA，深圳SZB)
		StringBuffer worldIndexDelayNames = itemNames[12];

		StringBuffer fxItems = itemNames[13]; // fx
		
		boolean isSubscribedOil = itemNames[14].toString().equals("true");
		
		StringBuffer indexFuturesCOPItems = itemNames[15];
		
		H_CODE statusCode;
		statusCode = H_CODE.NONE;
		
		requestCount = 0;
		fields_list.clear();
		
//		if (itemNames[0] != null) // stock
//		{
//			statusCode = HttpAppInfo.SendBMPStockMonitorRequest(actContext, itemNames[0].toString(), this, "Stock");
//			requestCount++;
//		}
//		if (itemNames[1] != null)
//		{
//			statusCode = HttpAppInfo.SendBMPMetalMonitorRequest(actContext, itemNames[1].toString(), this, "Metal");
//			requestCount++;
//		}
//		if (itemNames[3] != null)
//		{
//			statusCode = HttpAppInfo.SendBMPFuturesMonitorRequest(actContext, itemNames[3].toString(), !((ITDLApplication)getApplicationContext()).getIsRealtimeFutures(), this, "Futures");
//			requestCount++;
//		}
//		if (itemNames[4] != null)
//		{
//			statusCode = HttpAppInfo.SendBMPIndexMonitorRequest(actContext, itemNames[4].toString(), this, "Index");
//			requestCount++;
//		}
//		if (itemNames[6] != null)
//		{
//			statusCode = HttpAppInfo.SendBMPWorldIndexSSEIMonitorRequest(actContext, itemNames[6].toString(), !((ITDLApplication)getApplicationContext()).getIsRealtimeSSEI(), this, "WorldIndexSSEI");
//			requestCount++;
//		}
//		if (itemNames[8] != null)
//		{
//			statusCode = HttpAppInfo.SendBMPWorldIndexMonitorRequest(actContext, itemNames[8].toString(), this, "WorldIndex");
//			requestCount++;
//		}
//		if (itemNames[10] != null)
//		{
//			statusCode = HttpAppInfo.SendBMPWorldFuturesMonitorRequest(actContext, itemNames[10].toString(), this, "WorldFutures");
//			requestCount++;
//		}
//		if (itemNames[11] != null)
//		{
//			statusCode = HttpAppInfo.SendBMPWorldIndexMonitorRequest(actContext, itemNames[11].toString(), this, "WorldIndexDelay");
//			requestCount++;
//		}
//		if (itemNames[13] != null)
//		{
//			statusCode = HttpAppInfo.SendBMPFXMonitorRequest(actContext, itemNames[13].toString(), this, "FX");
//			requestCount++;
//		}
//		if (isSubscribedOil)
//		{
//			statusCode = HttpAppInfo.SendBMPOilMonitorRequest(actContext, this, "Oil");
//			requestCount++;
//		}
		
		/*-------------Monitor All-----------*/
		String futuresOrCopCode = "";
		if(indexFuturesItems != null)
		{
			futuresOrCopCode = indexFuturesItems.toString();
		}
		if(indexFuturesCOPItems != null)
		{
			if("".equals(futuresOrCopCode))
			{
				futuresOrCopCode = indexFuturesCOPItems.toString();
			}
			else
			{
				futuresOrCopCode += ",";
				String[] cops = indexFuturesCOPItems.toString().split(",");
				for(int i=0;i<cops.length;i++)
				{
					if(!futuresOrCopCode.contains(cops[i]))
					{
						futuresOrCopCode += ("," + cops[i]);
					}
				}
			}
		}
		
		String worldIndexCode = "";
		if(worldIndexItems != null)
		{
			worldIndexCode = worldIndexItems.toString();
		}
		if(worldIndexDelayItems != null)
		{
			if(!"".equals(worldIndexCode))
			{
				worldIndexCode += ",";
			}
			worldIndexCode += worldIndexDelayItems;
		}
		if(worldIndexDelayRealtimeItems != null)
		{
			if(!"".equals(worldIndexCode))
			{
				worldIndexCode += ",";
			}
			worldIndexCode += worldIndexDelayRealtimeItems;
		}
//		if(!"".equals(worldIndexCode))
//		{
//			statusCode = HttpAppInfo.SendBMPWorldIndexMonitorRequest(actContext, worldIndexCode, this, "WorldIndexOther");
//			requestCount++;
//		}
		
		final String[] iTypeName = 
		{
			stockItems == null ? "" : stockItems.toString(),
			indexItems == null ? "" : indexItems.toString(),
			worldIndexCode,
			/*worldIndexDelayRealtimeItems == null ? "" : worldIndexDelayRealtimeItems.toString(),*/
			/*indexFuturesItems == null ? "" : indexFuturesItems.toString(),*/
			futuresOrCopCode,
			worldIndexFuturesItems == null ? "" : worldIndexFuturesItems.toString(),
			fxItems == null ? "" : fxItems.toString(),
			goldInfoItems == null ? "" : goldInfoItems.toString(),
			isSubscribedOil ? "LCOIL" : ""
		};
		TDStockLog.d(TAG, "MonitorAll Request=>" + iTypeName[0].split(",").length + "," + iTypeName[1].split(",").length+","+iTypeName[2].split(",").length+","+iTypeName[3].split(",").length
				+","+iTypeName[4].split(",").length+","+iTypeName[5].split(",").length+ ","+iTypeName[6].split(",").length+","+iTypeName[7].split(",").length);
		
		boolean iSendRequest = false;
		for(int i = 0; i < iTypeName.length; i++)
		{
			if(!"".equals(iTypeName[i]))
			{
				iSendRequest = true;
				break;
			}
		}
		if(iSendRequest)
		{
			statusCode = HttpAppInfo.SendBMPMonitorPageAllRequest(actContext, iTypeName, this, "Monitor");
			requestCount++;
		}
		
		TDStockLog.d(TAG, "requestCount="+requestCount);
		
		return statusCode;
	}
	@Override
	public void H_UserClient_HttpRequest_Response(final H_UserClient_HttpRequest_Result iResult)
	{
		TDStockLog.d(TAG, "SeqID=>" + iResult.seqID);
		
		if(requestCount > 0)
			requestCount--;	
		
		TDStockLog.d(TAG, "requestCount="+requestCount);
		
		if(iShowProgressView && requestCount == 0)
			progressView.DismissProgress();
		
		if(iHConnectIsDestory)
			return;
		
		H_UserClient_HttpRequest_Response_Sub(iResult);
	}
	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(final H_UserClient_HttpRequest_Result iResult)
	{
		TDStockLog.d(TAG, TAG+"---->H_UserClient_HttpRequest_Response_Sub");
		if(!iResult.MStatus.equals("0"))
		{
			ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
			return;
		}
		

		if ("item".equals(iResult.seqID))
		{
			_monitorItemFromServer = iResult.contentStores;
			if (BMPPortfolioActivity.class.getSimpleName().equals(_cameFrom))
			{
				_editMonitorBtn.setVisibility(View.VISIBLE);
				_editMonitorBtn
						.setText(_isEditing ? R.string.monitor_finish
								: R.string.monitor_edit);

				if (_monitorItemFromServer == null
						|| _monitorItemFromServer.size() < 1)
				{
					_monitorList.clear();
					_listView.setClickable(false);
					_monitor_item_Adapter.notifyDataSetChanged();
					_listView.setClickable(true);
					return;
				}
			}

			if (System.currentTimeMillis() - lastRunntimeInOnResume < 1000l
					&& lastRunntimeInOnResume != 1l)
			{
				for (MonitorViewHolder holder : _monitorList)
				{
					holder.isEditable = _isEditing;
				}
				_monitor_item_Adapter.notifyDataSetChanged();
				return;
			} // don't execute twice during a short term
			lastRunntimeInOnResume = System.currentTimeMillis();

			if (_dropList != null)
			{
				_dropList.clear();
			}

			resetTable();

			if (_iconTip != null && mWindowManager != null)
			{
				mWindowManager.removeViewImmediate(_iconTip);
				_iconTip = null;
			}
			if (BMPBaseActivity._iconTip != null
					&& BMPBaseActivity.mWindowManager != null)
			{
				BMPBaseActivity.mWindowManager
						.removeViewImmediate(BMPBaseActivity._iconTip);
				BMPBaseActivity._iconTip = null;
			}

			if (_isEditing)
			{
				_isEditing = false;
				// Reset Item to non-editing mdode
				_listView.SetEditingMode(_isEditing);
			}
			_editMonitorBtn.setText(_isEditing ? R.string.monitor_finish
					: R.string.monitor_edit);

			loadDataUpdateUI(_cameFrom); // get data update ui

		}
		else
		{
			if (iResult.objMapStores.size() <= 0
					&& iResult.objArrayStores.length <= 0)
			{
				return;
			}
			final Runnable runnable = new Runnable()
			{
				@Override
				public void run()
				{
					updateDataByIdentify(iResult.objMapStores,
							iResult.seqID, iResult.objArrayStores);
				}
			};
			new Thread()
			{
				@Override
				public void run()
				{
					_messageHandler.post(runnable);
				}
			}.start();
		}
	}
	
	private List<String[]> fields_list = new ArrayList<String[]>();
	
	private void updateDataByIdentify(Map<String, ?> objMapStores, String iSeqID, Object[] iObjArrayStores)
	{
		if(itemNames == null) 
			return;
		
		Map<String, Stock> stockList = null;
		Map<String, Index> indexList = null;
		Map<String, Futures> futuresList = null;
		Map<String, WorldFutures> worldFuturesList = null;
		Map<String, WorldIndex> worldIndexList_ssei = null;
		Map<String, WorldIndex> worldIndexList_other = null;
		Map<String, WorldIndex> worldIndexList_delay = null; 
		Map<String, Metal> metalList = null;
		Map<String, Fx> fxList = null;
		Oil	oil = null;
		String serverTime = null;
		
		StringBuffer stockItems = itemNames[0]; // stock

		StringBuffer goldInfoItems = itemNames[1]; // gold
		StringBuffer goldNames = itemNames[2];

		StringBuffer indexFuturesItems = itemNames[3]; // futures

		StringBuffer indexItems = itemNames[4]; // index
		StringBuffer indexNames = itemNames[5];

		/* "上証SSEI" by ouyangzhihui 2011-08-25 */
		StringBuffer worldIndexDelayRealtimeItems = itemNames[6];// worldIndexSSEI
		StringBuffer worldIndexDelayRealtimeNames = itemNames[7];

		StringBuffer worldIndexItems = itemNames[8]; // wordIndexOther
		StringBuffer worldIndexNames = itemNames[9];

		StringBuffer worldIndexFuturesItems = itemNames[10]; // worldFutures

		StringBuffer worldIndexDelayItems = itemNames[11]; // worldIndex(深圳SZA，深圳SZB)
		StringBuffer worldIndexDelayNames = itemNames[12];

		StringBuffer fxItems = itemNames[13]; // fx
		
		StringBuffer indexFuturesCOPItems = itemNames[15];
		
//		if("Stock".equals(iSeqID))
//		{
//			stockList = (Map<String, Stock>) objMapStores;
//			for (int i = 0; i < stockList.size(); i++)
//			{
//				String[]fields = OnUpdateStock(stockList.get(stockItems.toString().split("[,]")[i]));
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
//		else if("Index".equals(iSeqID))
//		{
//			indexList = (Map<String, Index>) objMapStores;
//			for (int i = 0; i < indexList.size(); i++)
//			{
//				Index index = indexList.get(indexItems.toString().split("[,]")[i]);
//				String[]fields = OnUpdateIndex(i, index.getName(), index, indexNames.toString().split("[,]"), IndexInfo.ADAPTER);
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
//		else if("Futures".equals(iSeqID))
//		{
//			futuresList = (Map<String, Futures>) objMapStores;
//			for (int i = 0; i < futuresList.size(); i++)
//			{
//				Futures futures = futuresList.get(indexFuturesItems.toString().split(",")[i]);
//				String[]fields = OnUpdateFutures(futures.getName(), futures);
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
//		else if("WorldFutures".equals(iSeqID))
//		{
//			worldFuturesList = (Map<String, WorldFutures>) objMapStores;
//			for (int i = 0; i < worldFuturesList.size(); i++)
//			{
//				WorldFutures worldFutures = worldFuturesList.get(worldIndexFuturesItems.toString().split("[,]")[i]);
//				String[]fields = OnUpdateFutures(worldFutures.getName(), worldFutures);
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
//		else if("WorldIndex".equals(iSeqID))
//		{
//			worldIndexList_other = (Map<String, WorldIndex>) objMapStores;
//			for (int i = 0; i < worldIndexList_other.size(); i++)
//			{
//				WorldIndex worldIndex = worldIndexList_other.get(worldIndexItems.toString().split("[,]")[i]);
//				String[]fields = OnUpdateIndex(i, worldIndex.getName(), worldIndex, worldIndexNames.toString().split("[,]"), WorldIndexInfo.ADAPTER);
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
//		else if("WorldIndexDelay".equals(iSeqID))
//		{
//			worldIndexList_delay = (Map<String, WorldIndex>) objMapStores;
//			for (int i = 0; i < worldIndexList_delay.size(); i++)
//			{
//				WorldIndex worldIndex = worldIndexList_delay.get(worldIndexDelayItems.toString().split("[,]")[i]);
//				String[]fields = OnUpdateIndex(i, worldIndex.getName(), worldIndex, worldIndexDelayNames.toString().split("[,]"), WorldIndexDelayInfo.ADAPTER);
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
//		else if("WorldIndexSSEI".equals(iSeqID))
//		{
//			worldIndexList_ssei = (Map<String, WorldIndex>) objMapStores;
//			String adapter = ((ITDLApplication) getApplicationContext()).getIsRealtimeSSEI() ? WorldIndexInfo.ADAPTER : WorldIndexDelayInfo.ADAPTER;
//			for (int i = 0; i < worldIndexList_ssei.size(); i++)
//			{
//				WorldIndex worldIndex = worldIndexList_ssei.get(worldIndexDelayRealtimeItems.toString().split("[,]")[i]);
//				String[]fields = OnUpdateIndex(i, worldIndex.getName(), worldIndex, worldIndexDelayRealtimeNames.toString().split("[,]"), adapter, "true");
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
//		else if("Metal".equals(iSeqID))
//		{
//			metalList = (Map<String, Metal>) objMapStores;
//			for (int i = 0; i < metalList.size(); i++)
//			{
//				String[]fields = OnUpdateGold(i, metalList.get(goldInfoItems.toString().split("[,]")[i]), goldNames.toString().split("[,]"));
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
//		else if("FX".equals(iSeqID))
//		{
//			fxList = (Map<String, Fx>) objMapStores;
//			for (int i = 0; i < fxList.size(); i++)
//			{
//				String[]fields = OnUpdateFx(fxList.get(fxItems.toString().split("[,]")[i]));
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
//		else if("Oil".equals(iSeqID))
//		{
//			oil = (Oil) objMapStores.get("LCOIL");
//			String[] fields = OnUpdateOil(oil);
//			if(fields != null)
//				fields_list.add(fields);
//		}
		
		//
//		if("WorldIndexOther".equals(iSeqID))
//		{
//			String worldIndexCode = "";
//			String worldIndexNameCode = "";
//			if(worldIndexItems != null)
//			{
//				worldIndexCode = worldIndexItems.toString();
//			}
//			if(worldIndexDelayItems != null)
//			{
//				if(!"".equals(worldIndexCode))
//				{
//					worldIndexCode += ",";
//				}
//				worldIndexCode += worldIndexDelayItems;
//			}
//			if(worldIndexNames != null)
//			{
//				worldIndexNameCode = worldIndexNames.toString();
//			}
//			if(worldIndexDelayNames != null)
//			{
//				if(!"".equals(worldIndexNameCode))
//				{
//					worldIndexNameCode += ",";
//				}
//				worldIndexNameCode += worldIndexDelayNames;
//			}
//			
//			worldIndexList_other = (Map<String, WorldIndex>) objMapStores;
//			for (int i = 0; i < worldIndexList_other.size(); i++)
//			{
//				String codeKey = worldIndexCode.split("[,]")[i];
//				String widAdapter = WorldIndexInfo.ADAPTER;
//				if(worldIndexDelayItems != null && worldIndexDelayItems.toString().contains(codeKey))
//				{
//					widAdapter = WorldIndexDelayInfo.ADAPTER;
//				}	
//				WorldIndex worldIndex = worldIndexList_other.get(codeKey);
//				String[]fields = OnUpdateIndex(i, worldIndex.getName(), worldIndex, worldIndexNameCode.split("[,]"), widAdapter);
//				if(fields != null)
//					fields_list.add(fields);
//			}
//		}
		
		//版塊數據處理callBack
		if("Monitor".equals(iSeqID))
		{
			try
			{
				//iObjArrayStores[0];
				stockList = (Map<String, Stock>)iObjArrayStores[0];
				indexList = (Map<String, Index>)iObjArrayStores[1];
				worldIndexList_ssei = (Map<String, WorldIndex>)iObjArrayStores[2];
				futuresList = (Map<String, Futures>)iObjArrayStores[3];
				worldFuturesList = (Map<String, WorldFutures>)iObjArrayStores[4];
				fxList = (Map<String, Fx>)iObjArrayStores[5];
				metalList = (Map<String, Metal>)iObjArrayStores[6];
				oil = (Oil) iObjArrayStores[7];
				serverTime = (String)iObjArrayStores[8];
				
				TDStockLog.d(TAG, "MonitorAll Respone=>" + stockList.size() + "," + indexList.size()+","+worldIndexList_ssei.size()+","+futuresList.size()
						+","+worldFuturesList.size()+","+fxList.size()+ ","+metalList.size()+","+(oil==null?"null":oil.getName())+","+serverTime);
				
				for (int i = 0; i < stockList.size(); i++)
				{
					try
					{
						Stock stock = stockList.get(stockItems.toString().split("[,]")[i]);
						if(stock == null)
							continue;
						String[]fields = OnUpdateStock(stock);
						if(fields != null)
							fields_list.add(fields);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
				for (int i = 0; i < indexList.size(); i++)
				{
					try
					{
						Index index = indexList.get(indexItems.toString().split("[,]")[i]);
						if(index == null)
							continue;
						TDStockLog.d(TAG, "Monitor=>Index:"+index.getName()+","+index.getLast());
						String[]fields = OnUpdateIndex(i, index.getName(), index, indexNames.toString().split("[,]"), IndexInfo.ADAPTER);
						if(fields != null)
							fields_list.add(fields);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
				
				if(indexFuturesItems != null)
				{
					for (int i = 0; i < indexFuturesItems.toString().split(",").length; i++)
					{
						try
						{
							Futures futures = futuresList.get(indexFuturesItems.toString().split(",")[i]);
							String[]fields = OnUpdateFutures(futures.getName(), futures);
							if(fields != null)
								fields_list.add(fields);
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
					}
				}
				if(indexFuturesCOPItems != null)
				{
					for (int i = 0; i < indexFuturesCOPItems.toString().split(",").length; i++)
					{
						try
						{
							Futures futures = futuresList.get(indexFuturesCOPItems.toString().split(",")[i]);
							String[]fields = OnUpdateFuturesCOP(futures.getName(), futures);
							if(fields != null)
								fields_list.add(fields);
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
					}
				}
				for (int i = 0; i < worldFuturesList.size(); i++)
				{
					try
					{
						WorldFutures worldFutures = worldFuturesList.get(worldIndexFuturesItems.toString().split("[,]")[i]);
						if(worldFutures == null)
							continue;
						TDStockLog.d(TAG, "Monitor=>WorldFutures:"+worldFutures.getName()+","+worldFutures.getLast());
						String[]fields = OnUpdateFutures(worldFutures.getName(), worldFutures);
						if(fields != null)
							fields_list.add(fields);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
//				String adapter = ((ITDLApplication) getApplicationContext()).getIsRealtimeSSEI() ? WorldIndexInfo.ADAPTER : WorldIndexDelayInfo.ADAPTER;
//				for (int i = 0; i < worldIndexList_ssei.size(); i++)
//				{
//					WorldIndex worldIndex = worldIndexList_ssei.get(worldIndexDelayRealtimeItems.toString().split("[,]")[i]);
//					TDStockLog.d(TAG, "Monitor=>WorldIndex:"+worldIndex.getName()+","+worldIndex.getLast());
//					String[]fields = OnUpdateIndex(i, worldIndex.getName(), worldIndex, worldIndexDelayRealtimeNames.toString().split("[,]"), adapter, "true");
//					if(fields != null)
//						fields_list.add(fields);
//				}
				
				String worldIndexCode = "";
				String worldIndexNameCode = "";
				if(worldIndexItems != null)
				{
					worldIndexCode = worldIndexItems.toString();
				}
				if(worldIndexDelayItems != null)
				{
					if(!"".equals(worldIndexCode))
					{
						worldIndexCode += ",";
					}
					worldIndexCode += worldIndexDelayItems;
				}
				if(worldIndexDelayRealtimeItems != null)
				{
					if(!"".equals(worldIndexCode))
					{
						worldIndexCode += ",";
					}
					worldIndexCode += worldIndexDelayRealtimeItems;
				}
				if(worldIndexNames != null)
				{
					worldIndexNameCode = worldIndexNames.toString();
				}
				if(worldIndexDelayNames != null)
				{
					if(!"".equals(worldIndexNameCode))
					{
						worldIndexNameCode += ",";
					}
					worldIndexNameCode += worldIndexDelayNames;
				}
				if(worldIndexDelayRealtimeNames != null)
				{
					if(!"".equals(worldIndexNameCode))
					{
						worldIndexNameCode += ",";
					}
					worldIndexNameCode += worldIndexDelayRealtimeNames;
				}
				for (int i = 0; i < worldIndexList_ssei.size(); i++)
				{
					try
					{
						String codeKey = worldIndexCode.split("[,]")[i];
						String widAdapter = WorldIndexInfo.ADAPTER;
						if(worldIndexDelayItems != null && worldIndexDelayItems.toString().contains(codeKey))
						{
							widAdapter = WorldIndexDelayInfo.ADAPTER;
						}
						else if(worldIndexDelayRealtimeItems != null && worldIndexDelayRealtimeItems.toString().contains(codeKey))
						{
							widAdapter = ((ITDLApplication) getApplicationContext()).getIsRealtimeSSEI() ? WorldIndexInfo.ADAPTER : WorldIndexDelayInfo.ADAPTER;
						}
						
						WorldIndex worldIndex = worldIndexList_ssei.get(codeKey);
						
						if(worldIndex == null)
							continue;
						
						TDStockLog.d(TAG, "Monitor=>WorldIndex:"+worldIndex.getName()+","+worldIndex.getLast());
						String[]fields = OnUpdateIndex(i, worldIndex.getName(), worldIndex, worldIndexNameCode.split("[,]"), widAdapter);
						if(fields != null)
							fields_list.add(fields);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
				for (int i = 0; i < metalList.size(); i++)
				{
					try
					{
						Metal metal = metalList.get(goldInfoItems.toString().split("[,]")[i]);
						if(metal == null)
							continue;
						TDStockLog.d(TAG, "Monitor=>Metal:"+metal.getName()+","+metal.getLast());
						String[]fields = OnUpdateGold(i, metal, goldNames.toString().split("[,]"));
						if(fields != null)
							fields_list.add(fields);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
				for (int i = 0; i < fxList.size(); i++)
				{
					try
					{
						Fx fx = fxList.get(fxItems.toString().split("[,]")[i]);
						if(fx == null)
							continue;
						TDStockLog.d(TAG, "Monitor=>Fx:"+fx.getName()+","+fx.getNet());
						String[]fields = OnUpdateFx(fx);
						if(fields != null)
							fields_list.add(fields);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
				if(oil != null)
				{
					try
					{
						TDStockLog.d(TAG, "Monitor=>Oil:"+oil.getName()+","+oil.getLast());
						String[] fields = OnUpdateOil(oil);
						if(fields != null)
							fields_list.add(fields);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		
		if(requestCount == 0)
			updateDataByAdapter(fields_list, serverTime);
	}
	
	private void updateDataByAdapter(final List<String[]> fields_list, final String serverTime)
	{
		final Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					_monitorList.clear();
					for(MonitorViewHolder viewHolder : _monitorLoadingList)
					{
						_monitorList.add(viewHolder);
					}
					_monitorLoadingList.clear();
					
//					GetTimeData();
					try
					{
						if(serverTime!=null)
						{
							String tmp = serverTime;
							if(serverTime != null && serverTime.length() > 1)
							{
								tmp = serverTime.substring(8, 10) + ":" + serverTime.substring(10, 12) + ":" + serverTime.substring(12, 14); 
							}
							syncServerTimer(tmp);
						}
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
					
					// update adapter
					for(int i = 0; i < fields_list.size(); i++)
					{
						updateAdapter(fields_list.get(i));
					}
					
					_listView.setClickable(false);
					_monitor_item_Adapter.notifyDataSetChanged();
					_listView.setClickable(true);
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
		};
		new Thread()
		{
			@Override
			public void run()
			{
				_messageHandler.post(runnable);
			}
		}.start();
	}
	
	
	public H_CODE GetBMPMonitorItemDataFromServer()
	{
		TDStockLog.d(TAG, TAG + "------>GetBMPMonitorItemDataFromServer");
		return HttpAppInfo.GetBookMark(actContext, this, "item");
	}
}
